简体   繁体   English

在ConcurrentHashMap中放置线程安全的同时增加当前值?

[英]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. 我有ConcurrentHashMapConncurentHashMap<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: 但在这种情况下首先发生了什么:

  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? 如果第二个场景是现实中发生的事情将使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM