In Java, is it safe to change a reference to a HashMap read concurrently

前端 未结 4 984
慢半拍i
慢半拍i 2020-12-15 07:08

I hope this isn\'t too silly a question...

I have code similar to the following in my project:

public class ConfigStore {

    public static class Co         


        
4条回答
  •  执念已碎
    2020-12-15 07:31

    No, this is not thread safe without volatile, even apart from the issues of seeing stale values. Even though there are no writes to the map itself, and reference assignment is atomic, the new Map<> has not been safely published.

    For an object to be safely published, it must be communicated to other threads using some mechanism that either establishes a happens-before relationship between the object construction, the reference publication and the reference read, or it must use a handful of narrower methods which are guaranteed to be safe for publishing:

    • Initializing an object reference from a static initializer.
    • Storing a reference to it into a final field.

    Neither of those two publication specific ways applies to you, so you'll need volatile to establish happens-before.

    Here is a longer version of this reasoning, including links to the JLS and some examples of real-world things that can happen if you don't publish safely.

    More details on safe publication can be found in JCIP (highly recommended), or here.

提交回复
热议问题