基于共享容器协同的多线程模式下的问题:
有时我们需要通过加锁把使用线程不安全的容器的代码改为使用线程安全容器的代码时,会有什么问题。
============ HashMap
private static HashMap<String , Integer> map = new HashMap<String, Integer>();
============ ConcurrentHashMap
来自技术书籍。
有时我们需要通过加锁把使用线程不安全的容器的代码改为使用线程安全容器的代码时,会有什么问题。
============ HashMap
private static HashMap<String , Integer> map = new HashMap<String, Integer>();
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
private static ConcurrentHashMap<String , Integer> map = new ConcurrentHashMap<String, Integer>();
public void add(String key){
Integer value = map.get(key);
if (value == null) {
map.put(key, 1);
} else {
map.put(key, value + 1);
}
}
来自技术书籍。