[英]Java ConcurrentHashMap and for each loop
假設我有以下ConcurrentHashMap
:
ConcurrentHashMap<Integer,String> identificationDocuments = new ConcurrentHashMap<Integer,String>();
identificationDocuments.put(1, "Passport");
identificationDocuments.put(2, "Driver's Licence");
如何使用 for each 循環安全地遍歷地圖並將每個條目的值附加到字符串?
ConcurrentHashMap
產生的迭代器是弱一致性的。 那是:
- 他們可以與其他操作同時進行
- 他們永遠不會拋出 ConcurrentModificationException
- 它們保證遍歷元素,因為它們在構造時就存在過一次,並且可能(但不保證)反映構造后的任何修改。
最后一個要點非常重要,迭代器在創建迭代器后的某個時間點返回地圖的視圖,以引用ConcurrentHashMap的javadoc的不同部分:
類似地,迭代器、拆分器和枚舉返回反映哈希表在迭代器/枚舉創建時或創建后的某個時刻的狀態的元素。
因此,當您遍歷如下所示的鍵集時,您需要仔細檢查該項目是否仍然存在於集合中:
for(Integer i: indentificationDocuments.keySet()){
// Below line could be a problem, get(i) may not exist anymore but may still be in view of the iterator
// someStringBuilder.append(indentificationDocuments.get(i));
// Next line would work
someStringBuilder.append(identificationDocuments.getOrDefault(i, ""));
}
將所有字符串附加到StringBuilder
本身的行為是安全的,只要您在一個線程上執行此操作或以線程安全的方式完全封裝StringBuilder
。
我不知道您是否真的在問這個問題,但是要遍歷您遍歷keySet()
任何地圖
StringBuffer result = new StringBuffer("");
for(Integer i: indentificationDocuments.keySet()){
result.append(indentificationDocuments.get(i));
}
return result.toString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.