【发布时间】:2017-01-21 13:50:35
【问题描述】:
我现在已经在 java 中开发了一个 LRU 缓存,请建议我必须根据多线程诅咒对其进行自定义,所以请告知我需要在下面的程序中进行哪些更改以使其对多线程环境安全,下面是我的代码..
import java.util.LinkedHashMap;
public class LRUCache extends LinkedHashMap<Integer, String> {
private static final long serialVersionUID = 1342L;
private int cacheSize;
//In overridden method, we are saying that, remove entry only when we have reached cacheSize.
//initialCapacity,loadFactor,accessOrder the ordering mode - true for
// access-order, false for insertion-order
public LRUCache(int size) {
super(size, 0.75f, true);
this.cacheSize = size;
}
@Override
// removeEldestEntry() should be overridden by the user, otherwise it will not
//remove the oldest object from the Map.
protected boolean removeEldestEntry(java.util.Map.Entry<Integer,String> eldest) {
return size() > cacheSize;
}
public static void main(String arg[]){
LRUCache lruCache = new LRUCache(2);
lruCache.put(1, "Object1");
lruCache.put(2, "Object2");
lruCache.put(3, "Object3");
System.out.println(lruCache);
}
}
【问题讨论】:
标签: java multithreading