gpt4 book ai didi

java - 关于Java中LRU Cache实现的问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:04:47 24 4
gpt4 key购买 nike

Java实现LRU Cache的标准示例指向示例depot url http://www.exampledepot.com/egs/java.util/coll_Cache.html

在下面的代码片段中添加一个新条目后,如何默认调用 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);

最佳答案

根据 Java API for LinkedHashMap :

The removeEldestEntry(Map.Entry) method may be overridden to impose a policy for removing stale mappings automatically when new mappings are added to the map.

具体来说:

This method is invoked by put and putAll after inserting a new entry into the map.

另请注意:

This method typically does not modify the map in any way, instead allowing the map to modify itself as directed by its return value. It is permitted for this method to modify the map directly, but if it does so, it must return false (indicating that the map should not attempt any further modification). The effects of returning true after modifying the map from within this method are unspecified.

关于java - 关于Java中LRU Cache实现的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1229780/

24 4 0
文章推荐: android - 控制相机的自动曝光
文章推荐: java - 正则表达式排除引号内的匹配项
文章推荐: java - 基于 Spring-MVC 注解的 bean 验证是否支持基于集合的属性? ( Spring -MVC)
文章推荐: java - 通用 Java 模式识别库——如 List 的正则表达式