일반 LinkedHashMap 를 이용한 LRU 캐쉬 구현

황제낙엽 2007.11.03 16:21 조회 수 : 774 추천:189

sitelink1 http://ukmie.tistory.com/88 
sitelink2  
sitelink3  
sitelink4  
sitelink5  
sitelink6  

LinkedHashMap 를 이용하여 간단하게 LRU(leat-recently-used) 캐쉬를 구현할 수 있다.
여러가지 캐쉬 알고리즘과 솔루션들을 상황에 따라 고를 수 있지만, 간단한 캐쉬 기능이 필요한 경우
유용하게 쓸수 있다.

 

·미리보기 | 소스복사·
 
  1. import java.util.LinkedHashMap;   
  2. import java.util.Collection;   
  3. import java.util.Map;   
  4. import java.util.ArrayList;   
  5.   
  6. public class LRUCache {   
  7.     private static final float hashTableLoadFactor = 0.75f;   
  8.   
  9.     private LinkedHashMap map;   
  10.   
  11.     private int cacheSize;   
  12.   
  13.     public LRUCache(int cacheSize) {   
  14.     this.cacheSize = cacheSize;   
  15.     int hashTableCapacity = (int) Math.ceil(cacheSize / hashTableLoadFactor) + 1;   
  16.     map = new LinkedHashMap(hashTableCapacity, hashTableLoadFactor, true) { // (an anonymous inner class)   
  17.         private static final long serialVersionUID = 1;   
  18.   
  19.         @Override   
  20.         protected boolean removeEldestEntry(Map.Entry eldest) {   
  21.             return size() > LRUCache.this.cacheSize;   
  22.         }   
  23.     };   
  24.     }   
  25.   
  26.     /**  
  27.      * The retrieved entry becomes the MRU (most recently used) entry.  
  28.      */  
  29.     public synchronized V get(K key) {   
  30.         return map.get(key);   
  31.     }   
  32.   
  33.     /**  
  34.          * If the cache is full, the LRU (least recently used) entry is dropped.  
  35.          */  
  36.     public synchronized void put(K key, V value) {   
  37.         map.put(key, value);   
  38.     }   
  39.   
  40.     public synchronized void clear() {   
  41.         map.clear();   
  42.     }   
  43.   
  44.     public synchronized int usedEntries() {   
  45.         return map.size();   
  46.     }   
  47.   
  48.     public synchronized Collection> getAll() {   
  49.         return new ArrayList>(map.entrySet());   
  50.     }   
  51.   
  52.     // 4test..!   
  53.     public static void main(String[] args) {   
  54.         LRUCache c = new LRUCache(3);   
  55.         c.put("1""one");         // 1   
  56.         c.put("2""two");         // 2 1   
  57.         c.put("3""three");       // 3 2 1   
  58.         c.put("4""four");        // 4 3 2   
  59.         if (c.get("2") == null)   
  60.             throw new Error();     // 2 4 3   
  61.         c.put("5""five");        // 5 2 4   
  62.         c.put("4""second four"); // 4 5 2   
  63.         // Verify cache content.   
  64.         if (c.usedEntries() != 3)   
  65.             throw new Error();   
  66.         if (!c.get("4").equals("second four"))   
  67.             throw new Error();   
  68.         if (!c.get("5").equals("five"))   
  69.             throw new Error();   
  70.         if (!c.get("2").equals("two"))   
  71.             throw new Error();   
  72.         // List cache content.   
  73.         for (Map.Entry e : c.getAll())   
  74.             System.out.println(e.getKey() + " : " + e.getValue());   
  75.     }   
  76. }  


참고:
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

 

번호 제목 글쓴이 날짜 조회 수
123 상속과 연관(association, composition) 황제낙엽 2008.04.10 444
122 HttpServletRequest 객체의 함수 모음 file 황제낙엽 2008.01.28 596
121 ObjectCache클래스 와 Server/Client프로그램 file 황제낙엽 2007.11.07 504
120 ObjectCache시스템의 구현을 위한 추가 고려사항 황제낙엽 2007.11.04 477
119 문제 : 간단한 ObjectCache 프로그램을 구현하라 황제낙엽 2007.11.01 581
118 ObjectCache 클래스를 구현한 예제 소스 파일들 황제낙엽 2007.11.01 448
» LinkedHashMap 를 이용한 LRU 캐쉬 구현 황제낙엽 2007.11.03 774
116 J2SE 5.0 에서의 QUEUE와 DELAYED 프로세싱 황제낙엽 2007.11.02 464
115 J2EE object-caching frameworks (ObjectCache) 황제낙엽 2007.11.02 1866
114 Object Caching in a Web Portal Application Using JCS (ObjectCache) 황제낙엽 2007.11.02 503
113 Java Object Cache | Patterns 'N J2EE (ObjectCache) 황제낙엽 2007.11.01 544
112 Runtime 클래스를 이용한 JVM 메모리 사용량 확인 황제낙엽 2007.11.05 485
111 자바 애플리케이션에서 동적으로 PDF 파일 생성하기 황제낙엽 2007.10.03 402
110 싱글사인온(single sign-on)으로 엔터프라이즈 자바 인증을 단순하게! 황제낙엽 2007.10.03 451
109 [BPP] 게시판 페이징 로직 분석 - M1.3 file 황제낙엽 2007.09.26 304
108 [HttpURLConnection] 2초후에 연결 끊어주는 URLConnection 예제 황제낙엽 2007.09.08 497
107 Assertions : 비교 확인, 조건 확인, Null 확인 황제낙엽 2007.09.02 436
106 [BPP] 게시판 페이징 로직 분석 - M1.2 - SQLMap(ibatis) 지원 file 황제낙엽 2007.08.29 349
105 J2SE 5.0 - 컨스턴트와 메서드에 static imports 사용하기 황제낙엽 2007.08.28 479
104 J2SE 5.0 - 향상된 루프문 황제낙엽 2007.08.27 460