[英]Is incrementing of current value while putting thread-safe in ConcurrentHashMap?
我想知道當我在將其放入ConcurrentHashMap
時修改當前值時會發生什么。
我有ConcurrentHashMap
( ConncurentHashMap<String, Integer> attendance
),其中包含會議廳名稱的現有映射和每個會員的訪客數量。
每次調用visit(conferenceHallName)
方法都應該增加給定會議廳的訪問者數量。 每個調用者都是一個線程。
所以這是方法:
public void visit(String conferenceHallName) {
attendance.put(conferenceHallName, attendance.get(conferenceHallName) + 1);
}
put()
是鎖定方法, get()
不是。 但在這種情況下首先發生了什么:
如果第二個場景是現實中發生的事情將使用AtomicInteger
而不是Integer
解決我的問題?
第二個描述更接近實際發生的情況:線程將以線程安全的方式訪問值,使用更新的計數構造新的Integer
,然后鎖定映射,並替換對象。
使用AtomicInteger
而不是Integer
將解決此問題:
attendance.get(conferenceHallName).getAndIncrement();
這假設所有conferenceHallName
鍵都在地圖中正確設置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.