【发布时间】:2009-08-04 20:31:11
【问题描述】:
Java实现LRU Cache的标准示例指向示例depot url http://www.exampledepot.com/egs/java.util/coll_Cache.html
在下面的代码 sn-p 中添加一个新条目后,默认情况下如何调用 removeEldestEntry?
final int MAX_ENTRIES = 100;
Map cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) {
// This method is called just after a new entry has been added
public boolean removeEldestEntry(Map.Entry eldest) {
return size() > MAX_ENTRIES;
}
};
// Add to cache
Object key = "key";
cache.put(key, object);
// Get object
Object o = cache.get(key);
if (o == null && !cache.containsKey(key)) {
// Object not in cache. If null is not a possible value in the cache,
// the call to cache.contains(key) is not needed
}
// If the cache is to be used by multiple threads,
// the cache must be wrapped with code to synchronize the methods
cache = (Map)Collections.synchronizedMap(cache);
【问题讨论】:
-
感谢您的回答!所以这是匿名内部类,我错过了。