Java examples for java.util.concurrent:ExecutorService
add Shutdown Hook
//package com.java2s; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; public class Main { private static void addShutdownHook( final ExecutorService executorService) { Runtime.getRuntime().addShutdownHook(new Thread() { @Override/*from w w w. j a v a 2 s.co m*/ public void run() { shutdown(executorService); } }); } public static void shutdown(final ExecutorService executorService) { executorService.shutdown(); try { int timeToWait = 30; if (!executorService.awaitTermination(timeToWait, TimeUnit.SECONDS)) { List<Runnable> executionList = executorService .shutdownNow(); for (Runnable runnable : executionList) { System.out.println("Trying to shutdown task: " + runnable); } } if (!executorService.awaitTermination(timeToWait, TimeUnit.SECONDS)) { } } catch (InterruptedException ex) { executorService.shutdownNow(); Thread.currentThread().interrupt(); } } }