Reputation: 43
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:
And if the second scenario is what happens in reality will using AtomicInteger
instead of Integer
solve my issue?
Upvotes: 4
Views: 150
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