使这个自定义 LinkedHashMap 自定义缓存示例线程安全的最佳方法是什么?
public class Cache extends LinkedHashMap<Object, Object>{
private static final long serialVersionUID = -4297992703249995219L;
private final int cacheSize;
public Cache(int size){
super(size + 1, .75f, true);
this.cacheSize=size;
}
protected boolean removeEldestEntry(Map.Entry<Object, Object> eldest) {
return size() > cacheSize;
}
}
public class Main {
public static void main(String[] args) {
Cache cache = new Cache(2);
cache.put(1, "one");
cache.put(2, "two");
for(Entry<Object, Object> entry : cache.entrySet()){
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}