下面這段代碼存在并發陷阱????
曾憲杰的《大型網站系統與Java中間件實踐》第一章第1.2.2.3小節給出以下代碼示例:
使用HashMap數據被進行統計;
public class TestClass { private HashMap<String, Integer> map = new HashMap<>();public synchronized void add(String key) { Integer value = map.get(key); if(value == null) { map.put(key, 1); } else { map.put(key, value + 1); } }}
使用ConcurrentHashMap保存數據并進行統計;
public class TestClass { private ConcurrentHashMap<String<愛尬聊_百科全書>, Integer> map = new ConcurrentHashMap<>();public void add(String key) { Integer value = map.get(key); if(value == null) { map.put(key, 1); } else { map.put(key, value + 1); } }}
使用HashMap時,對add方法加鎖,此時該方法是線程安全的,為何換為ConcurrentHashMap之后,原書中說存在并發陷阱???
zzw2888 1天前
為何換為ConcurrentHashMap之后,還要對add方法進行加鎖???
fkylily 1天前
沒加鎖啊。
