HashMap 和 concurrentHaspMap 的陷阱与区别
2017-09-10 17:39
615 查看
在多线程并发编程中,我们对于共享的数据对象或者是容器会采用线程安全的集合来存储。Java中 提供了一些线程安全的容器和对象,有些事支持并发的,java.util.concurrent 包中 有很多这样的类。这种方式的效率会比简单的加互斥锁的实现更好,但是有时通过加锁把使用线程不安全的容器代码改为使用线程安全容器的代码时,会遇到一个陷阱。
在一个使用map 存储信息后 ,统计总数的例子中。
一:map 中的value 整型使用线程不安全的hashMap代码时这样写的。
二:使用concurrentHashMap 来替换hashMap 并且是仅仅去掉synchronized 关键字 那么问题就出现了。问题不复杂,大家可以自己来思考答案。
会出现使用concurrentHashMap 统计的总数 永远比使用hashMap统计总数多一。那么问题究竟出现在了那里?
在一个使用map 存储信息后 ,统计总数的例子中。
一:map 中的value 整型使用线程不安全的hashMap代码时这样写的。
private HashMap<String,Integer> map= new HashMap<String, Integer>(); public synchronized void add1(String key){ Integer value=map.get(key); if(value==null){ map.put(key,1); }else{ map.put(key,value+1); } }
二:使用concurrentHashMap 来替换hashMap 并且是仅仅去掉synchronized 关键字 那么问题就出现了。问题不复杂,大家可以自己来思考答案。
private ConcurrentHashMap<String,Integer> conMap= new ConcurrentHashMap<String, Integer>(); public void add2(String key){ Integer value=conMap.get(key); if(value==null){ conMap.put(key,1); }else{ conMap.put(key,value+1); } }
会出现使用concurrentHashMap 统计的总数 永远比使用hashMap统计总数多一。那么问题究竟出现在了那里?
相关文章推荐
- HashMap HashTable ConcurrentHashMap区别
- (转载)ConcurrentHaspLRUHashMap实现初探
- hashmap,hashTable concurrentHashMap 是否为线程安全,区别,如何实现的
- J2EE HashTable跟HaspMap的区别
- ConcurrentHashMap putIfAbsent和的put区别
- 【JAVA秒会技术之ConcurrentHashMap】JDK1.7与JDK1.8源码区别
- Vector ArrayList linkedlist set hashtable hashmap concurrenthashmap 的区别
- HashMap的非线程安全性和ConcurrentHasMap
- HashMap HashTable ConcurrentHashMap 区别
- hashmap hashtable concurrenthashmap的区别
- HashMap与Has和Table的区别
- ConcurrentHaspLRUHashMap实现初探
- JAVA中HashMap和Hashtable区别
- LinkedHashMap和HashMap的区别以及使用方法
- HashMap和Hashtable的区别
- 源码解析之 HashMap与HashTable的区别
- 浅析java中ArrayList与Vector的区别以及HashMap与Hashtable的区别
- HashMap、hashtable以及ConcurrentHashMap的区别
- HashMap和Hashtable的区别
- Java集合类ArrayList,Vector,HashMap,Hashtable区别