Is ExecutorService (specifically ThreadPoolExecutor) thread safe?

(Contrary to other answers) the thread-safety contract is documented: look in the interface javadocs (as opposed to javadoc of methods). For example, at the bottom of the ExecutorService javadoc you find:

Memory consistency effects: Actions in a thread prior to the
submission of a Runnable or Callable task to an ExecutorService
happen-before any actions taken by that task, which in turn
happen-before the result is retrieved via Future.get().

This is sufficient to answer this:

“do I have to synchronize access to the executor before interacting/submitting tasks?”

No you don’t. It is fine to construct and submit jobs to any (correctly implemented) ExecutorService without external synchronisation. This is one of the main design goals.

ExecutorService is a concurrent utility, which is to say that it is designed to operate to the greatest extent without requiring synchronisation, for performance. (Synchronisation causes thread-contention, which can degrade multi-threading efficiency – particularly when scaling up to a large number of threads.)

There is no guarantee about at what time in the future the tasks will execute or complete (some may even execute immediately on same thread that submitted them) however the worker thread is guaranteed to have seen all effects that the submitting thread has performed up to the point of submission. Therefore (the thread that runs) your task can also safely read any data created for its use without synchronisation, thread-safe classes or any other forms of “safe publication”. The act of submitting the task is itself sufficient for “safe publication” of the input data to the task. You just need to ensure that the input data won’t be modified in any way while the task is running.

Similarly, when you fetch the result of the task back via Future.get(), the retrieving thread will be guaranteed to see all effects made by the executor’s worker thread (in both the returned result, plus any side-effect changes the worker-thread may have made).

This contract also implies that it is fine for the tasks themselves to submit more tasks.

“Does the ExecutorService guarantee thread safety ?”

Now this part of the question is much more general. For example could not find any statement of a thread-safety contract about the method shutdownAndAwaitTermination – although I note that the code sample in the Javadoc does not use synchronisation. (Although perhaps there’s a hidden assumption that the shutdown is instigated by the same thread that created the Executor, and not for example a worker thread?)

BTW I’d recommend the book “Java Concurrency In Practice” for a good grounder on the world of concurrent programming.

Leave a Comment