Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 732
Marin Veršić Avatar asked Apr 23 '26 04:04

Marin Veršić


2 Answers

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.

like image 192
JB Nizet Avatar answered Apr 25 '26 18:04

JB Nizet


If you declare and initialize your HashMap as static field it will be initialized by Java class loader in a thread safe fashion.

like image 36
Andrei Amarfii Avatar answered Apr 25 '26 17:04

Andrei Amarfii