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 万,因为客户手机文件也差不多这个数量,结果还是没问题。
所以我想问一下,有办法复现吗?