原理是使用linkedhashmap来实现,当缓存超过大小时,将会删除最老的一个元组。
实现代码如下所示
import java.util.linkedhashmap;
import java.util.map;
public class lrucache {
public static class cacheddata {
private object data = null;
private long time = 0;
private boolean refreshing = false;
public cacheddata(object data) {
this.data = data;
this.time = system.currenttimemillis();
}
public object getdata() {
return data;
}
public long gettime() {
return time;
}
public void settime(long time) {
this.time = time;
}
public boolean getrefreshing() {
return refreshing;
}
public void setrefreshing(boolean b) {
this.refreshing = b;
}
}
protected static class cachemap extends linkedhashmap {
protected int maxsize = 0;
public cachemap(int maxsize) {
super(maxsize * 4 / 3 + 1, 0.75f, true);
this.maxsize = maxsize;
}
protected boolean removeeldestentry(map.entry eldest) {
return size() > this.maxsize;
}
}
protected cachemap map = null;
public lrucache(int size) {
this.map = new cachemap(size);
}
public synchronized void set(object key, object value) {
map.remove(key);
map.put(key, new cacheddata(value));
}
public synchronized void remove(object key) {
map.remove(key);
}
public synchronized cacheddata get(object key) {
cacheddata value = (cacheddata) map.get(key);
if (value == null) {
return null;
}
map.remove(key);
map.put(key, value);
return value;
}
public int usage() {
return map.size();
}
public int capacity() {
return map.maxsize;
}
public void clear() {
map.clear();
}
}
如对本文有疑问,
点击进行留言回复!!
相关文章:
-
-
-
-
-
-
-
Java人机猜拳
实现:User类public class User {private String name;private i...
[阅读全文]
-
-
-
-
网友评论