如何創建一個線程安全的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