001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 *     http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014package org.gbif.utils.concurrent;
015
016import java.util.concurrent.ExecutorService;
017import java.util.concurrent.Executors;
018import java.util.concurrent.TimeUnit;
019
020import org.junit.jupiter.api.Test;
021
022import static org.junit.jupiter.api.Assertions.assertTrue;
023
024public class ExecutorUtilsTest {
025
026  @Test
027  public void stopEmptyExec() {
028    ExecutorService exec = Executors.newFixedThreadPool(2, new NamedThreadFactory("tata"));
029
030    ExecutorUtils.stop(exec, 1, TimeUnit.SECONDS);
031    assertTrue(exec.isTerminated());
032  }
033
034  @Test
035  public void stopExecWithJobs() throws Exception {
036    ExecutorService exec = Executors.newFixedThreadPool(2, new NamedThreadFactory("tata"));
037    exec.submit(new DontStop());
038    exec.submit(new DontStop());
039    exec.submit(new DontStop());
040
041    ExecutorUtils.stop(exec, 1, TimeUnit.SECONDS);
042    Thread.sleep(1000);
043    assertTrue(exec.isTerminated());
044  }
045
046  class DontStop implements Runnable {
047
048    @Override
049    public void run() {
050      long x = 0;
051      while (true) {
052        if (x == Long.MAX_VALUE) {
053          x = Long.MIN_VALUE;
054        }
055        x++;
056        try {
057          Thread.sleep(10);
058        } catch (InterruptedException e) {
059          throw new RuntimeException(e);
060        }
061      }
062    }
063  }
064}