ConcurrentModificationException with LinkedHashMap

后端 未结 6 662
北恋
北恋 2021-02-04 03:09

Not sure what is triggering a java.util.ConcurrentModificationException when I iterate over the LinkedHashMap structure in the code below. Using the

6条回答
  •  情歌与酒
    2021-02-04 03:27

    Your code

    for(String key : lru_cache.keySet()){
        System.out.println(lru_cache.get(key));
    }
    

    Actually compiles to:

    Iterator it = lru_cache.keySet().iterator();
    while (it.hasNext()) {
        String key = it.next();
        System.out.println(lru_cache.get(key));
    }
    

    Next, your LRU cache shrinks itself to MAX_SIZE elements not when calling set(), but when calling get() - above answers explain why.

    Thus we have following behavior:

    • new iterator created to iterate over lru_cache.keySet() collection
    • lru_cache.get() called to extract element from your cache
    • get() invocation truncates lru_cache to MAX_SIZE elements (in your case 3)
    • iterator it becomes invalid due to collection modification and throws on next iteration.

提交回复
热议问题