线程安全的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修饰,会有什么问题,为什么?

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

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

没啥问题

ConcurrentHashmap线程安全的,采用的是分段锁形式;不像hashTable是只有一把锁