The following code demonstrates creating a thread pool with a fictitious task running, this task is then launched, and when the application terminates, a stop hook is triggered, which cancels all tasks that are performed and closes the thread pool cleanly.
You do not need to use Callable, like me, you can use Runnables and the threadPool.execute method and just terminate threadPool, which is a little less elegant.
final ExecutorService threadPool = Executors.newCachedThreadPool();
final List<Future<Void>> runningTasks = new ArrayList<>();
Future<Void> task = threadPool.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
int count = 0;
while(true) {
System.out.println(++count);
Thread.sleep(1000);
}
}
});
runningTasks.add(task);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
for(Future<Void> runningTask : runningTasks) {
runningTask.cancel(true);
}
threadPool.shutdownNow();
}
});
. Java EE javax.servlet.ServletContextListener