LinkedHashMap 를 이용하여 간단하게 LRU(leat-recently-used) 캐쉬를 구현할 수 있다.
여러가지 캐쉬 알고리즘과 솔루션들을 상황에 따라 고를 수 있지만, 간단한 캐쉬 기능이 필요한 경우
유용하게 쓸수 있다.
import java.util.LinkedHashMap;
import java.util.Collection;
import java.util.Map;
import java.util.ArrayList;public class LRUCache<K,V> {private static final float hashTableLoadFactor = 0.75f;private LinkedHashMap<K,V> map;
private int cacheSize;
public LRUCache (int cacheSize) {
this.cacheSize = cacheSize;
int hashTableCapacity = (int)Math.ceil(cacheSize / hashTableLoadFactor) + 1;
map = new LinkedHashMap<K,V>(hashTableCapacity, hashTableLoadFactor, true) {
// (an anonymous inner class)
private static final long serialVersionUID = 1;
@Override protected boolean removeEldestEntry (Map.Entry<K,V> eldest) {
return size() > LRUCache.this.cacheSize; }}; }/**
* The retrieved entry becomes the MRU (most recently used) entry.
*/
public synchronized V get (K key) {
return map.get(key); }/**
* If the cache is full, the LRU (least recently used) entry is dropped.
*/
public synchronized void put (K key, V value) {
map.put (key,value); }public synchronized void clear() {
map.clear(); }public synchronized int usedEntries() {
return map.size(); }public synchronized Collection<Map.Entry<K,V>> getAll() {
return new ArrayList<Map.Entry<K,V>>(map.entrySet());
}
// 4test..!
public static void main (String[] args) {
LRUCache<String,String> c = new LRUCache<String,String>(3);
c.put ("1","one"); // 1
c.put ("2","two"); // 2 1
c.put ("3","three"); // 3 2 1
c.put ("4","four"); // 4 3 2
if (c.get("2")==null) throw new Error(); // 2 4 3
c.put ("5","five"); // 5 2 4
c.put ("4","second four"); // 4 5 2
// Verify cache content.
if (c.usedEntries() != 3) throw new Error();
if (!c.get("4").equals("second four")) throw new Error();
if (!c.get("5").equals("five")) throw new Error();
if (!c.get("2").equals("two")) throw new Error();
// List cache content.
for (Map.Entry<String,String> e : c.getAll())
System.out.println (e.getKey() + " : " + e.getValue());
}}참고: http://www.source-code.biz/snippets/java/6.htm
http://dojeun.egloos.com/317868
http://java.sun.com/j2se/1.4.2/docs/api/java/util/LinkedHashMap.html