Search code examples
javamultithreadingvolatile

Java forcing volatile access


Consider a situation like this.

There are two threads and a shared resource(like a HashMap). One thread created the HashMap and initialized it with some key-value pairs and after the shared resource is initialized it will never be modified again.

Now, the second thread is created strictly after the shared resource is initialized and wants to use that resource. At this point I would like some guarantee that the second thread will use the correct version of the shared resource. I presume it is possible that the first thread didn't flush the changes to the main memory before the second thread is created so the second thread will take the old value of the shared resource to it's cache.

Is this analysis correct, and how to force flush to main memory in Java by hand after initializing the shared resource as in this particular situation where I do not want or require volatile or synchronized.


Solution

  • The documentation says:

    A call to start on a thread happens-before any action in the started thread.

    So, if your code matches your description, it's safe.