Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ConcurrentHashMap actions atomicity

This may be a duplicate question, but I've found this part of code in a book about concurrency. This is said to be thread-safe:

ConcurrentHashMap<String, Integer> counts = new ...;

private void countThing(String thing) {
    while (true) {
        Integer currentCount = counts.get(thing);
        if (currentCount == null) {
            if (counts.putIfAbsent(thing, 1) == null)
                break;
        } else if (counts.replace(thing, currentCount, currentCount + 1)) {
            break;
        }
    }
}

From my (concurrency beginners') point of view, thread t1 and thread t2 could both read currentCount = 1. Then both threads could change the maps' value to 2. Can someone please explain me if the code is okay or not?

like image 975
insan-e Avatar asked Jul 03 '16 01:07

insan-e


People also ask

Is ConcurrentHashMap put Atomic?

My question is method put() in ConcurrentHashMap also atomic? Yes, The entire method invocation is performed atomically.

Can 2 threads perform write operations on same ConcurrentHashMap object?

Having two threads that change the map at the very same point time is not possible. Because the code within that ConcurrentHashMap will not allow two threads to manipulate things in parallel!

Can multiple threads read ConcurrentHashMap at the same time?

Size of Segments and concurrency level of ConcurrentHashMap By default ConcurrentHashMap has segment array size as 16 so simultaneously 16 Threads can put data in map considering each thread is working on separate Segment array index.


1 Answers

The trick is that replace(K key, V oldValue, V newValue) provides the atomicity for you. From the docs (emphasis mine):

Replaces the entry for a key only if currently mapped to a given value. ... the action is performed atomically.

The key word is "atomically." Within replace, the "check if the old value is what we expect, and only if it is, replace it" happens as a single chunk of work, with no other threads able to interleave with it. It's up to the implementation to do whatever synchronization it needs to make sure that it provides this atomicity.

So, it can't be that both threads see currentAction == 1 from within the replace function. One of them will see it as 1, and thus its invocation to replace will return true. The other will see it as 2 (because of the first call), and thus return false — and loop back to try again, this time with the new value of currentAction == 2.

Of course, it could be that a third thread has updated currentAction to 3 in the meanwhile, in which case that second thread will just keep trying until it's lucky enough to not have anyone jump ahead of it.

like image 125
yshavit Avatar answered Sep 22 '22 08:09

yshavit