一個LRU算法的實現

LRU是Least Recently Used的縮寫,即最近最少使用頁面置換算法,是爲虛擬頁式存儲管理服務的。該算法的初衷是有內存管理而被提出來的,其目的是爲解決“如何節省利用容量不大的內存爲最多的進程提供資源”時如何減少過多的讓進程去讀取外存。
這裏以鏈表法來實現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();
}
}
發佈了16 篇原創文章 · 獲贊 0 · 訪問量 3578
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章