weixin_48477226 2021-03-25 15:27 采纳率: 66.7%
浏览 63
已采纳

线程安全的ConcurrentHashMap和线程不安全的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);
        }
        
    }

}

使用线程不安全的hashmap,add方法使用synchronized修饰。现在我将代码修改一下成为下图:

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);
        }
    }

}

使用线程安全的ConcurrentHashMap,方法上不使用synchronized修饰,会有什么问题,为什么?

  • 写回答

4条回答 默认 最新

  • CPoet 2021-03-25 16:07
    关注

    方法上加的时候,get和put能保证数据一致性。

    第二个,你在下一次get之后,put之前可能会发生中断。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?