Failing to call shutdown()
on a thread executor will result in a never terminating application.
Best practice to shut down the ExecutorService is this:
ExecutorService service = null;
try {
service = Executors.newSingleThreadExecutor();
// add tasks to thread executor
…
} finally {
if (service != null) service.shutdown();
}
Since Java knows the try-with-resources concept, wouldn't it be nice if we could do this?
try (service = Executors.newSingleThreadExecutor())
{
// add tasks to thread executor
…
}
Closeable
APIs in the JDK – Hershelhershell