[英]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
. 我想知道当我在将其放入
ConcurrentHashMap
时修改当前值时会发生什么。
I have ConcurrentHashMap
( ConncurentHashMap<String, Integer> attendance
) with existing mapping of conference hall names and number of visitors to each. 我有
ConcurrentHashMap
( ConncurentHashMap<String, Integer> attendance
),其中包含会议厅名称的现有映射和每个会员的访客数量。
Every invocation of visit(conferenceHallName)
method is supposed to increment the number of visitors to the given conference hall. 每次调用
visit(conferenceHallName)
方法都应该增加给定会议厅的访问者数量。 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. put()
是锁定方法, get()
不是。 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? 如果第二个场景是现实中发生的事情将使用
AtomicInteger
而不是Integer
解决我的问题?
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. 第二个描述更接近实际发生的情况:线程将以线程安全的方式访问值,使用更新的计数构造新的
Integer
,然后锁定映射,并替换对象。
Using AtomicInteger
instead of Integer
will solve the issue: 使用
AtomicInteger
而不是Integer
将解决此问题:
attendance.get(conferenceHallName).getAndIncrement();
This is assuming that all conferenceHallName
keys are properly set in the map. 这假设所有
conferenceHallName
键都在地图中正确设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.