LRU是Least Recently Used的缩写,即最近最少使用,是一种常用的页面置换算法,选择最近最久未使用的页面予以淘汰。该算法赋予每个页面一个访问字段,用来记录一个页面自上次被访问以来所经历的时间 t,当须淘汰一个页面时,选择现有页面中其 t 值最大的,即最近最少使用的页面予以淘汰。
public class Lru{
private Hashtable<Object,Node> hashtable=new Hashtable<>();
private Node head;
private Node tail;
private int count;
private int maxCapacity;
public Lru() {
this.maxCapacity=Integer.MAX_VALUE;
}
public Lru(int maxCapacity) {
this.maxCapacity = maxCapacity;
}
public boolean isEmpty(){
return count==0;
}
public int size(){
return count;
}
public void set(Object k,Object v){
Node node = hashtable.get(k);
if(null!=node){
node.setValue(v);
node.getPre().setNext(node.getNext());
node.setNext(head);
head=node;
}
else {
Node newNode = new Node(k, v, null, null);
if(head==null){
head=newNode;
tail=newNode;
}
else {
newNode.setNext(head);
head.setPre(newNode);
head=newNode;
}
hashtable.put(k,newNode);
}
if(++count>maxCapacity){
removeLast();
}
}
public Object get(Object k){
Node node = hashtable.get(k);
if(null==node){
return null;
}
else if(head.getKey()==k){
return head.getValue();
}
else {
moveToHead(node);
return node.getValue();
}
}
private void moveToHead(Node node) {
node.getPre().setNext(node.getNext());
node.setNext(head);
head=node;
}
private void removeLast(){
hashtable.remove(tail.getKey());
Node tailPre = tail.getPre();
tailPre.setNext(null);
tail=tailPre;
count--;
}
}
class Node{
private Object key;
private Object value;
private Node pre;
private Node next;
public Node() {
}
public Node(Object key, Object value, Node pre, Node next) {
this.key = key;
this.value = value;
this.pre = pre;
this.next = next;
}
public Object getKey() {
return key;
}
public void setKey(Object key) {
this.key = key;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public Node getPre() {
return pre;
}
public void setPre(Node pre) {
this.pre = pre;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}