Skip to content

Commit

Permalink
fix(common): ConcurrentModificationException in LruCache
Browse files Browse the repository at this point in the history
LruCache.release -> inner.entrySet.iterator.next -> afterExpired.accept -> channel.close -> closeFutureListener.operationComplete -> LruCache.remove -> inner.remove
				 -> inner.entrySet.iterator.next -> throw ConcurrentModificationException
  • Loading branch information
Zmax0 committed Jun 7, 2024
1 parent f0568be commit 8167dda
Showing 1 changed file with 3 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import io.netty.util.Timeout;

import java.time.Duration;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
Expand All @@ -16,7 +15,7 @@ public class LruCache<K, V> {
final Duration timeToLive;
final HashedWheelTimer timer = new HashedWheelTimer(1, TimeUnit.SECONDS);
final BiConsumer<K, V> afterExpired;
final Map<K, Pair<V>> inner = Collections.synchronizedMap(new LinkedHashMap<>() {
final Map<K, Pair<V>> inner = new LinkedHashMap<>() {
@Override
protected boolean removeEldestEntry(Map.Entry<K, Pair<V>> eldest) {
boolean flag = size() > capacity;
Expand All @@ -28,7 +27,7 @@ protected boolean removeEldestEntry(Map.Entry<K, Pair<V>> eldest) {
}
return flag;
}
});
};

public LruCache(long capacity, Duration timeToLive, BiConsumer<K, V> afterExpired) {
this.capacity = capacity;
Expand Down Expand Up @@ -73,7 +72,7 @@ public V remove(K key) {
}

public void release() {
for (Map.Entry<K, Pair<V>> entry : inner.entrySet()) {
for (Map.Entry<K, Pair<V>> entry : Map.copyOf(inner).entrySet()) {
afterExpired.accept(entry.getKey(), entry.getValue().value);
}
timer.stop();
Expand Down

0 comments on commit 8167dda

Please sign in to comment.