ExecutorServiceUtils { public static void shutdownAndAwaitTermination(ExecutorService pool, long timeout, TimeUnit unit) { pool.shutdown(); try { if (!pool.awaitTermination(timeout, unit)) { pool.shutdownNow(); if (!pool.awaitTermination(timeout, unit)) System.err.println("Pool did not terminate"); } } catch (InterruptedException ie) { pool.shutdownNow(); Thread.currentThread().interrupt(); } }  static void shutdownAndAwaitTermination(ExecutorService pool, long timeout, TimeUnit unit);  }
@Test void testShutdownAndAwaitTermination() { int threadNum = 2; int count = 10; long taskTime = 500L; long maxTime = taskTime * count / threadNum; ExecutorService pool = Executors.newFixedThreadPool(threadNum); AtomicInteger maxTask = new AtomicInteger(count); for (int i = 0; i < count; i++) { pool.submit(() -> { try { Thread.sleep(taskTime); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("task complete. " + maxTask.getAndDecrement()); }); } shutdownAndAwaitTermination(pool, maxTime + 100, TimeUnit.MILLISECONDS); assertEquals(0, maxTask.get()); }