我是新來的線程在Java中,我需要從少數活動線程訪問數據結構。我聽說java.util.concurrent.ConcurrentHashMap對線程友好。在訪問ConcurrentHashMap時,我是否需要使用synchronized(map){}
或者它會自行處理鎖?使用ConcurrentHashMap
2
A
回答
4
它處理鎖本身,而事實上你必須給他們無權訪問(有沒有其他的選項)
可以在特殊情況下的寫入使用,但它是非常罕見的,你應該需要做這個。例如如果您需要實施自己的putIfAbsent
,因爲創建對象的成本很高。
使用syncrhonized進行讀操作會失敗使用併發集合的目的。
2
簡答:不,您不需要使用synchronized(map)
。
龍回答:
- 所有
ConcurrentHashMap
提供的操作是線程安全的,你可以叫他們不用擔心鎖定 - 但是,如果你需要一些操作在你的代碼的原子,你仍然需要某種鎖定在客戶端
2
不,您不需要,但如果您需要依賴內部同步,則應該使用Collections.synchronizedMap
來代替。來自javadoc的ConcurrentHashMap
:
該類與Hashtable在依賴其線程安全性但不依賴於其同步細節的程序中完全可互操作。
其實它不會對整個數據結構,但在它的子部分(一些桶)同步。 這意味着ConcurrentHashMap
的迭代器是弱一致的,並且映射的大小可能不準確。 (但是另一方面,它的運行仍然是一致的,並且吞吐量更高)
3
ConcurrentHashMap
僅適用於您不需要任何更多原子性而不是提供開箱即用的情況。例如,如果你需要得到的值,用它做什麼,然後設置一個新的值,都在一個原子操作,這不能沒有外部鎖定實現。
在所有這些情況下沒有任何東西可以在你的代碼替換明確的鎖,它只不過是浪費使用此實現,而不是基本HashMap
的。
-1
還有一個更重要的功能要注意併發除併發功能它提供的功能,它是故障安全迭代器。只是因爲他們想要編輯的的entrySet PUT /而迭代刪除使用CHMP。 Collections.synchronizedMap(Map)
是另一個。但是ConcurrentModificationException可能出現在上述情況中。
相關問題
- 1. 當使用的ConcurrentHashMap
- 2. 高效使用ConcurrentHashMap?
- 3. concurrenthashmap java
- 4. ConcurrentHashMap Iteration
- 5. ConcurrentHashMap parallelismThreshold
- 6. 爲什麼ConcurrentHashMap :: putIfAbsent比ConcurrentHashMap :: computeIfAbsent更快?
- 7. 使用ConcurrentHashMap的數據不一致
- 8. 併發問題使用ConcurrentHashMap時
- 9. 的`ConcurrentHashMap`迭代多線程使用
- 10. 重疊ConcurrentHashMap放入使用putIfAbsent
- 11. 使用ConcurrentHashMap,何時需要同步?
- 12. 場景:爲什麼要使用ConcurrentHashMap?
- 13. 使用ConcurrentHashMap進行多線程
- 14. 如何在Scala中使用ConcurrentHashMap computeIfAbsent()
- 15. ConcurrentHashMap vs Synchronized HashMap
- 16. 迭代的ConcurrentHashMap
- 17. 迭代的ConcurrentHashMap
- 18. 的ConcurrentHashMap操作
- 19. 克隆ConcurrentHashMap
- 20. ConcurrentHashMap ArrayList爲值
- 21. ConcurrentHashMap到HashMap
- 22. ConcurrentHashMap Locks增加
- 23. Java ConcurrentHashmap問題
- 24. 迭代的ConcurrentHashMap
- 25. Java - ThreadLocal vs ConcurrentHashMap
- 26. Java中的ConcurrentHashMap?
- 27. ConcurrentHashMap的示例
- 28. Servlet中的ConcurrentHashMap
- 29. ConcurrentHashMap鎖定
- 30. 按值過濾ConcurrentHashMap
另外'putIfAbsent'執行原子,這在某些情況下,非常有用。 – stemm