removeEldestEntry在使用put或者putAll方法插入一个新的entry到map中时被调用,是否要删除年老的entry取决于是否满足既定的条件(比如本例中的条件:MAP中entry数量大于1000)。如果MAP表示缓存,这是有用的:它允许MAP通过删除过时条目来减少内存消耗。
import java.util.LinkedHashMap; import java.util.Map; public class LruCache { private final Map<Object, Object> store; private static final int MAX = 1000; public LruCache() { this.store = new LinkedHashMap<Object, Object>() { private static final long serialVersionUID = -3834209229668463829L;; /** * 当满足一定条件时删除Map中的年老的Entry */ @Override protected boolean removeEldestEntry(Entry<Object, Object> eldest) { return size() > MAX; } }; } public void put(Object key, Object value) { synchronized (LruCache.class) { store.put(key, value); } } public Object get(Object key) { synchronized (LruCache.class) { return store.get(key); } } }