Search code examples
javamultithreadinginterfacetry-with-resources

Why does the ExecutorService interface not implement AutoCloseable?


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
  …
} 

Solution

  • That ExecutorService has actually two shutdown-related methods; based on the simple fact that both ways of shutting down a service make sense.

    Thus: how would you auto-close a service then? In a consistent manner that works for everybody?!

    So, the reasonable explanation in my eyes: you can't make an ExecutorService a AutoClosable because that service does not have a single "close" like operation; but two!

    And if you think you could make good use of such an auto-closing service, writing up your own implementation using "delegation" would be a 5 minute thing! Or probably 10 minutes, because you would create one version calling shutdown() as close operation; and one that does shutdownNow() instead.