Is ExecutorService (specifically ThreadPoolExecutor) thread safe?

Solution 1:

(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.

Solution 2:

It's true, the JDK classes in question don't seem to make an explicit guarantee of thread-safe task submission. However, in practice, all ExecutorService implementations in the library are indeed thread-safe in this way. I think it's reasonable to depend on this. Since all the code implementing these features was placed in the public domain, there's absolutely no motivation for anyone to completely rewrite it a different way.

Solution 3:

Your question is rather open-ended: All the ExecutorService interface does is guarantee that some thread somewhere will process the submitted Runnable or Callable instance.

If the submitted Runnable / Callable references a shared data structure that is accessible from other Runnable / Callables instances (potentially being processed simulataneously by different threads), then it is your responsibility to ensure thread safety across this data structure.

To answer the second part of your question, yes you will have access to the ThreadPoolExecutor before submitting any tasks; e.g.

BlockingQueue<Runnable> workQ = new LinkedBlockingQueue<Runnable>();
ExecutorService execService = new ThreadPoolExecutor(4, 4, 0L, TimeUnit.SECONDS, workQ);
...
execService.submit(new Callable(...));

EDIT

Based on Brian's comment and in case I've misunderstood your question: Submission of tasks from multiple producer threads to the ExecutorService will typically be thread-safe (despite not being mentioned explicitly in the interface's API as far as I can tell). Any implementation that didn't offer thread safety would be useless in a multi-threaded environment (as multiple producers / multiple consumers is a fairly common paradigm), and this is specifically what ExecutorService (and the rest of java.util.concurrent) was designed for.