For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries. 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. They do not throw ConcurrentModificationException. However, iterators are designed to be used by only one thread at a time.
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html
经 V 友提醒,去看了下 javadoc ,然后发现了这句描述,于是决定复现:
public class Main {
private static ConcurrentHashMap<String,String> concurrentHashMap = new ConcurrentHashMap<>();
public static void main(String[] args) {
for(int i = 0 ; i < 100000 ; i++){
concurrentHashMap.put("Key"+i,"Value"+i);
}
new Thread(new Runnable() {
@Override
public void run() {
for (Map.Entry<String, String> entry : concurrentHashMap.entrySet()){
System.out.println("1key:"+entry.getKey()+",value:"+entry.getValue());
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for (Map.Entry<String, String> entry : concurrentHashMap.entrySet()){
System.out.println("2key:"+entry.getKey()+",value:"+entry.getValue());
}
}
}).start();
new Thread(new Runnable() {
结果还是没有任何问题。然后我还有用线程在这个多线程遍历的同时去给其增加删除元素,量级也是 10 万,因为客户手机文件也差不多这个数量,结果还是没问题。
所以我想问一下,有办法复现吗?
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.