Tuesday 15 February 2011

java - Is setting a hashmap thread safe? -


I have a hampp in my program that is accessed by several threads, and sometimes set by a thread .

For example: Maps & lt; String, string & gt; MyMap = New Hashmop & lt; String, string & gt; ();

This is accessed by several threads. Once an hour, call a thread:

  myMap = myRefreshedVersionOfTheMap;   

So my question is whether this thread is safe or not. If both the map is always the key "important key" , then what is possible is that once the "important key" is not present for the reading thread, the map Can access?

Edit:

Thanks for the reply, I have realized that it is actually free from the Hashmap. This object had more questions about reference assignments.

This thread is not secure even after the point of publication no letter is written for the map (From publication of thread publication), and reference assignment is atomic, new map & lt; & Gt; is not safely published This specially, there you write on the map during your construction - either in the constructor or after, how do you add those elements , And what they write can be seen or not by other threads, even if they are intuitively before the maps are published on other threads, it is not formally according to the memory model. .

To safely publish an object, it should be communicated to the outside world using a mechanism, that is, before relations between object creation, reference publication and context , Or to install it, or use some narrow methods that are guaranteed to be secure for publication:

  • An object from a constant initiator Start the reference.
  • Store a reference in this last field.

    If you have declared my map instability then be safe, more information about secure publication (highly recommended), or on this topic can be found. .

No comments:

Post a Comment