ConcurrentHashMap isn't always enough - DZone
The atomicity of computeIfAbsent(..)
assures that only one new Object
will be created and put into theMap
, and it'll be the exact same instance of Object
that will be returned to all threads calling the getOrCreate
function.
Here, not only the code is correct, it's also cleaner and much shorter.
The point of this example was to introduce a common pitfall of blindly relying on ConcurrentHashMap
as a majical synchronzed datastructure which is threadsafe and therefore should solve all our concurrency issues regarding multiple threads working on a shared Map
. ConcurrentHashMap
is, indeed, threadsafe. But it only means that all read/write operations on such map are internally synchronized. And sometimes it's just not enough for our concurrent environment needs, and we have to use some special treatment which will guarantee atomic execution. A good practice will be to use one of the atomic methods implemented by ConcurrentHashMap
, i.e: computeIfAbsent(..)
, putIfAbsent(..)
, etc.
Read full article from ConcurrentHashMap isn't always enough - DZone
No comments:
Post a Comment