Tuesday, October 6, 2015

get/put method of ConcurrentHashMap is not thread safe

The code below is not thread safe.
Some programmers are surprised that a supposedly threadsafe data structure permits operations that are not threadsafe. But there are two entirely different considerations. If multiple threads modify a plain HashMap, they can destroy the internal structure (an array of linked lists). Some of the links may go missing, or even go in circles, rendering the data structure unusable. That will never happen with a ConcurrentHashMap. In the example above, the code for get and put will never corrupt the data structure. But, since the sequence of operations is not atomic, the result is not predictable.
you can use a ConcurrentHashMap or, with Java 8, a ConcurrentHashMap. Then the update code is:
Java 8 provides methods that make atomic updates more convenient. The compute method is called with a key and a function to compute the new value. That function receives the key and the associated value, or null if there is none, and it computes the new value. For example, here is how we can update a map of integer counters:
There are also variants computeIfPresent and computeIfAbsent that only compute a new value when there is already an old one, or when there isn’t yet one. A map of LongAdder counters can be updated with CAUTION: When you use compute or merge, keep in mind that the function that you supply should not do a lot of work.While that function runs, some other updates to the map may be blocked. Of course, that function should also not update other parts of the map.

No comments:

Post a Comment