Java中简单易用的LRU缓存

Java中简单易用的LRU缓存,第1张

Java中简单易用的LRU缓存

您可以使用linkedHashMap(Java 1.4+):

// Create cachefinal 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 cacheObject key = "key";cache.put(key, object);// Get objectObject 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 pre to synchronize the methodscache = (Map)Collections.synchronizedMap(cache);


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5426919.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存