Not sure what is triggering a java.util.ConcurrentModificationException
when I iterate over the LinkedHashMap
structure in the code below. Using the
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:
lru_cache.keySet()
collectionlru_cache.get()
called to extract element from your cacheget()
invocation truncates lru_cache
to MAX_SIZE elements (in your case 3)it
becomes invalid due to collection modification and throws on next iteration.