Is setting a HashMap thread safe?

后端 未结 4 2024
北荒
北荒 2021-02-20 10:39

I have a HashMap in my program which is accessed by multiple threads, and is occasionally set by a single thread.

For example:

Map

        
4条回答
  •  Happy的楠姐
    2021-02-20 10:47

    This is not thread safe. Even though there are no writes to the map itself after the point of publication (from the point of view of the thread doing the publication), and reference assignment is atomic, the new Map<> has not been safely published. It particular, there are writes to the Map during its construction - either in the constructor, or after, depending on how you add those elements, and those writes may or may not be seen by other threads, since even though they intuitively occur before the map is published to the other threads, this isn't formally the case according to the memory model.

    For an object to be safely published, it must be communicated to the outside world 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.

    Your idiom would be safe if you declared myMap volatile. More details on safe publication can be found in JCIP (highly recommended), or here, or in this longer answer on a similar topic.

提交回复
热议问题