java容器迭代或序列化時不允許修改操作
原因:迭代或序列化前後會查看modCount
是否發生變化,如果發生變化,意味着容器結構發生變化,會拋出一個ConcurrentModificationException
異常;容器在遍歷時結構變化會發生一些不可控的問題。
具體化:
- LikedList和LinkedHashMap、LinkedHashSet在使用Lru順序前提下,遍歷和序列化時不允許put,remove,get操作;
- 其他情況迭代或序列化時不允許put,remove操作
public class LRUCache<K,V> extends LinkedHashMap<K,V> {
private static final int MAX_ENTRIES = 3;//設置緩存空間容量爲3
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > MAX_ENTRIES;// 結點數大於MAX_ENTRIES時返回true移除最近最久未使用的節點
}
LRUCache(){
super(MAX_ENTRIES,0.75f,true);//將accessOrder設置爲 true,開啓 LRU 順序;
}
public static void main(String[] args) {
LRUCache<String,Integer> cache = new LRUCache<>();
cache.put("Tom",25);
cache.put("Mary",24);
cache.put("David",26);
cache.get("Tom");
cache.put("James",33);
// System.out.println(cache.entrySet());
for (String k : cache.keySet()) {
System.out.println(cache.get(k));
}
}
}
Exception in thread "main" java.util.ConcurrentModificationException
26
at java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:719)
at java.util.LinkedHashMap$LinkedKeyIterator.next(LinkedHashMap.java:742)
at collection.LRUCache.main(LRUCache.java:25)
- ps:在遍歷LinkedHashMap過程中是不會改變Lru順序的(只有put和get會改變)