Java hash map thread visibility

I fully loaded a Java HashMap during initialization, but after initializing multiple threads, the HashMap will read the data I want to avoid any kind of synchronization because maps are basically read-only and never change But can I guarantee that all threads can see all keys and values?

Solution

If the contents of the map never change, you have no problem Memory model visibility issues only come into play when the contents of variables change

You may want to synchronize the initialization of the map to ensure that no thread accesses it before full initialization and that the values loaded into the map are visible

Editor: originally, I completely ignored the problem of how to initialize the map Reading one of the Pugh articles (again) it seems that the map really needs to be final so that the initialization data becomes visible:

There is a condition that lists the mandatory "first occurrence" relationship, which is given in the Java specification. I should quote it here (or if someone is in his answer, I will vote) Static variables and idioms are certainly one way The question is quite extensive because it does not specify how the map is initialized. If you publish a question describing how you propose initialization, you may get a more direct and useful answer

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>