如何创建一个线程安全的Map?


1,使用普通的旧的Hashtable

  HashMap允许null作为key,而Hashtable不可以

2,使用Collections中同步化的包装方法synchronizedMap

3,使用concurrent包下的ConcurrentHashMap 

//Hashtable Example Code
Map<String, Integer> threadSafeMap = new Hashtable<String, Integer>();
//synchronizedMap Example Code.
threadSafeMap = Collections.synchronizedMap(new HashMap<String, Integer>());
//ConcurrentHashMap Example Code
threadSafeMap = new ConcurrentHashMap<String, Integer>();
threadSafeMap .put("Key1", 123)

ConcurrentHashMap 性能最好

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM