I have a HashMap
in my program which is accessed by multiple threads, and is occasionally set by a single thread.
For example:
Map
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:
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.