I read somewhere that starting a thread has some special effect on the happend before relationship. Now I’m not sure if my code gurantees the happend before relationship, so please enlighten me.
I have a Dispatcher thread and a Worker class implementing the Runnable interface. The Dispatcher thread creates a new instance of the Worker and fills a LinkedList in the Worker instance through the add method with elements.
Then the Dispatcher hands the Worker instance to a ExecutorService via the execute method.
Then the run method in the Worker class starts accessing and removing stuff from the LinkedList.
Does the freshly started instance of the Worker see the same state of the LinkedList as the Dispatcher left it in? Or could it be that LinkedList is in some inconsitent state? Will I have to fill the LinkedList in a sychronized method?
The Java Language Specification writes:
However, from your description it is not clear whether that is relevant in your case, as you talk about an executor, but don’t explain when that executor is created or its worker threads started.
What is relevant is the following exerpt from Executor’s JavaDoc:
Hence your code is safe, as long as the dispatcher thread no longer accesses the list after submitting the
Runnable.