Skip to content

Instantly share code, notes, and snippets.

@SergeyAlekseevN
Last active January 10, 2019 10:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SergeyAlekseevN/7959b8e4c3c28ca7fb231337b6129f21 to your computer and use it in GitHub Desktop.
Save SergeyAlekseevN/7959b8e4c3c28ca7fb231337b6129f21 to your computer and use it in GitHub Desktop.
The following method shuts down an ExecutorService in two phases, first by calling shutdown to reject incoming tasks, and then calling shutdownNow, if necessary, to cancel any lingering tasks:
void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment