Serj Rud
Serj Rud

Reputation: 43

Is incrementing of current value while putting thread-safe in ConcurrentHashMap?

I wonder what happens when I modify current value while putting it into ConcurrentHashMap.

I have ConcurrentHashMap (ConncurentHashMap<String, Integer> attendance) with existing mapping of conference hall names and number of visitors to each.

Every invocation of visit(conferenceHallName) method is supposed to increment the number of visitors to the given conference hall. Every invoker is a thread.

So here is the method:

public void visit(String conferenceHallName) {    
   attendance.put(conferenceHallName, attendance.get(conferenceHallName) + 1);    
}

put() is locking method, get() is not. But what happens first in this case:

  1. thread will lock segment with this mapping, then calculate a new value and then put and release which is perfect for me or
  2. thread will get the old value, calculate a new one, then lock segment and put which means inconsistency for me and I will need to find a workaround.

And if the second scenario is what happens in reality will using AtomicInteger instead of Integer solve my issue?

Upvotes: 4

Views: 150

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

The second description is closer to what actually happens: the thread will access the value in a thread-safe way, construct a new Integer with the updated count, then lock the map, and replace the object.

Using AtomicInteger instead of Integer will solve the issue:

attendance.get(conferenceHallName).getAndIncrement();

This is assuming that all conferenceHallName keys are properly set in the map.

Upvotes: 3

Related Questions