I have been reading for concurency since yesterday and i dont know much things… However some things are starting to getting clear…
I understand why double check locking isnt safe (i wonder what is the propability the rare condition to occur) but volatile fixes the issue in 1.5 +….
But i wonder if this occurs with putifAbsent
like…
myObj = new myObject("CodeMonkey");
cHashM.putIfAbsent("keyy",myObj);
Then does this ensures that myObj would be 100% intialiased when another thread does a cHashM.get() ??? Because it could have a reference isnt completely initialised (the double check lock problem)
If you invoke
concurrentHashMap.get(key)and it returns an object, that object is guaranteed to be fully initialized. Each put (or putIfAbsent) will obtain a bucket specific lock and will append the element to the bucket’s entries.Now you may go through the code and notice that the get method doesnt obtain this same lock. So you can argue that there can be an out of date read, that isn’t true either. The reason here is that value within the entry itself is volatile. So you will be sure to get the most up to date read.