Removing all queued tasks of an ThreadPoolExecutor
I used to work on an app with long running threads. We do this at shutdown,
BlockingQueue<Runnable> queue = threadPool.getQueue();List<Runnable> list = new ArrayList<Runnable>();int tasks = queue.drainTo(list);
The list is saved to a file. On startup, the list is added back to the pool so we don't lose any jobs.
Have you considered wrapping the ExecutorService? Create a
CleanShutdownExecutorService implements Executor
that delegates all calls to another Executor, but keeps the Futures in a list of its own. CleanShutdownExecutorService can then have a cancelRemainingTasks() method that calls shutdown(), then calls cancel(false) on all the Futures in its list.
As ExecutorService.shutdown() is not doing enough and ExecutorService.shutdownNow() is doing too much I guess you have to write up something in the middle: remember all your submitted tasks and remove them manually after (or before) calling shutdown()
.