Java ConcurrentHashMap和每个循环 [英] Java ConcurrentHashMap and for each loop

查看:47
本文介绍了Java ConcurrentHashMap和每个循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下 ConcurrentHashMap :

ConcurrentHashMap<Integer,String> identificationDocuments = new ConcurrentHashMap<Integer,String>();
        
identificationDocuments.put(1, "Passport");
identificationDocuments.put(2, "Driver's Licence");

如何安全地在for每个循环中遍历地图,并将每个条目的值附加到字符串之后?

How would I safely iterate over the map with a for each loop and append the value of each entry to a string?

推荐答案

ConcurrentHashMap 生成的迭代器为

Iterators produced by a ConcurrentHashMap are weakly consistent. That is:

  • 它们可以与其他操作同时进行
  • 他们永远不会抛出ConcurrentModificationException
  • 保证它们遍历完构建时已经存在的元素一次,并且可能(但不保证)反映出构建后的任何修改.

最后一个要点非常重要,迭代器自创建迭代器以来就在某个点返回地图视图,以引用

The last bullet-point is pretty important, an iterator returns a view of the map at some point since the creation of the iterator, to quote a different section of the javadocs for ConcurrentHashMap:

类似地,迭代器,拆分器和枚举返回的元素反映了在创建迭代器/枚举时或创建哈希表时的某个时刻的哈希表状态.

Similarly, Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration.

因此,当您遍历如下所示的键集时,需要仔细检查该项目是否仍存在于集合中:

So when you loop through a keyset like the following, you need to double check if the item still exists in the collection:

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 完全封装在一个线程中安全的方式.

The act of appending all the strings to the StringBuilder itself is safe, as long as you are doing it on one thread or have encapsulated the StringBuilder entirely in a thread-safe manner.

这篇关于Java ConcurrentHashMap和每个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆