這裏以鏈表法來實現LRU:
一點介紹
操作系統爲每個進程維護一條鏈表,鏈表的每個結點記錄一張頁面的地址。調用一次頁面,則把該頁面的結點從鏈中取出,放到鏈尾;要裝入新頁,則把鏈頭的頁面調出,同時生成調入頁面的結點,放到鏈尾。
LRU算法的理論基礎是:局部性原理
/*
*Created on 2008-7-24
*/
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;
/**
* @author anwx<a href="mailto:[email protected]">An Weixiao</a>
* @version $Id$
*/
public class LRUTest {
protected HashMap<Object, Serializable> cache;
protected Vector<Object> cacheList;
protected int capacity = 3;
private int getCapacity(){
return this.capacity;
}
private int getSize(){
return cache.size();
}
public LRUTest(){
this.cache = new HashMap<Object, Serializable>();
this.cacheList = new Vector<Object>();
}
private void moveToTop(Object identifier) {
cacheList.insertElementAt(identifier,0);
if ( getSize() >= getCapacity() ) {
String toBeDeleted = (String)cacheList.lastElement();
cache.remove(toBeDeleted);
int lastElement = cacheList.size();
cacheList.remove(lastElement-1);
}
}
public Object get(Object identifier) {
if ( cache.containsKey(identifier) ) {
moveToTop(identifier);
Serializable co = (Serializable)cache.get(identifier);
return co;
}
else {
return null;
}
}
public void put(Object identifier, Serializable value) {
if ( getSize() < getCapacity() ) {
if ( !cache.containsKey(identifier) ) {
cacheList.insertElementAt(identifier,0);
}
cache.put(identifier,value);
}
else {
cache.put(identifier,value);
moveToTop(identifier);
}
}
private void print(){
System.out.println("data, key in cache");
Object key = null;
Serializable value = null;
for(Iterator it = cache.keySet().iterator(); it.hasNext();){
key = it.next();
System.out.println(String.format("[%s, %s]", cache.get(key), key));
}
System.out.println("key info sequence");
for(Object o: cacheList){
System.out.println(o);
}
}
public static void main(String args[]){
LRUTest test = new LRUTest();
test.put("1", "a");
test.put("2", "b");
test.put("3", "c");
test.print();
test.put("4", "d");
test.put("5", "e");
test.print();
}
}