org.snapscript.common.LeastRecentlyUsedMap Maven / Gradle / Ivy
package org.snapscript.common;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
public class LeastRecentlyUsedMap extends LinkedHashMap {
private final RemovalListener removalListener;
private final int capacity;
public LeastRecentlyUsedMap() {
this(null);
}
public LeastRecentlyUsedMap(int capacity) {
this(null, capacity);
}
public LeastRecentlyUsedMap(RemovalListener removalListener) {
this(removalListener, 100);
}
public LeastRecentlyUsedMap(RemovalListener removalListener, int capacity) {
this.removalListener = removalListener;
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Entry eldest) {
int size = size();
if (size <= capacity) {
return false;
}
if (removalListener != null) {
V value = eldest.getValue();
K key = eldest.getKey();
removalListener.notifyRemoved(key, value);
}
return true;
}
public static interface RemovalListener {
public void notifyRemoved(K key, V value);
}
}