Java Memory Model happens-before guarantees for Thread Pool interactions
I think that it is guaranteed to be visible. ExecutorService
extends Executor
, and the javadocs for Executor
say:
Memory consistency effects: Actions in a thread prior to submitting a
Runnable
object to anExecutor
happen-before its execution begins, perhaps in another thread.
By my reading, that matches what is going on in your example. The write
runnable is submitting the read
runnable, so there is a happens-before relationship between events before the submission in the write
thread (i.e. the set
call) and the events afterwards in the read
thread (i.e. the get
call).
The fact that the write
runnable is itself submitted means that there is also a happens-before between the creation of the Container
object and the call to set
.
Quoting javadoc of ExecutorService
:
Memory consistency effects: Actions in a thread prior to the submission of a
Runnable
orCallable
task to anExecutorService
happen-before any actions taken by that task, which in turn happen-before the result is retrieved viaFuture.get()
.
But, it says nothing about two tasks added to the queue, and whether processing of task 1 happens-before processing of task 2, as seen from the task. Only that adding the task to the queue happens before the task processing it, and the task execution happens before the result is retrieved by the original invoker.
Update
There is no happens-before correlation between two different, independently submitted tasks, even if somehow one is known the run to completion before the other begins running.
Of course, when one task submits another, as is done in the question, any action taken in task 1 before it submits task 2, will happen-before the execution of task 2.
If task 1 continues to do other stuff after submitting task 2, there is of course no happen-before guarantee, because task 2 may run and complete before task 1 gets to continue it's work.