KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > cache > LRUCache


1 // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
2

3 package jodd.cache;
4
5 import java.util.LinkedHashMap JavaDoc;
6 import java.util.Map JavaDoc;
7 import java.util.Iterator JavaDoc;
8
9
10 /**
11  * LRU (least recently used) cache.
12  *
13  * <p>
14  * Items are added to the cache as they are accessed; when the cache is full, the least recently used item is ejected.
15  * This type of cache is typically implemented as a linked list, so that an item in cache, when it is accessed again,
16  * can be moved back up to the head of the queue; items are ejected from the tail of the queue. Cache access overhead
17  * is again constant time. This algorithm is simple and fast, and it has a significant advantage over FIFO in being
18  * able to adapt somewhat to the data access pattern; frequently used items are less likely to be
19  * ejected from the cache. The main disadvantage is that it can still get filled up with items that are
20  * unlikely to be reaccessed soon; in particular, it can become useless in the face of scanning type accesses.
21  * Nonetheless, this is by far the most frequently used caching algorithm.<br>
22  * Summary for LRU: fast, adaptive, not scan resistant.
23  */

24 public class LRUCache extends AbstractCacheMap {
25
26     public LRUCache(int cacheSize) {
27         this(cacheSize, 0);
28     }
29
30     /**
31      * Creates a new LRU cache.
32      */

33     public LRUCache(int cacheSize, long timeout) {
34         this.cacheSize = cacheSize;
35         this.timeout = timeout;
36         cacheMap = new LinkedHashMap JavaDoc(cacheSize + 1, 1.0f, true) {
37             protected boolean removeEldestEntry(Map.Entry JavaDoc eldest) {
38                 return size() > LRUCache.this.cacheSize;
39             }
40         };
41     }
42
43
44     // ---------------------------------------------------------------- prune
45

46     /**
47      * Prune only expired objects, LinkedHashMap will take car of LRU if needed.
48      */

49     public synchronized int prune() {
50         if (isPruneExpiredActive() == false) {
51             return 0;
52         }
53         int count = 0;
54         Iterator JavaDoc values = cacheMap.values().iterator();
55         while (values.hasNext()) {
56             CacheObject co = (CacheObject) values.next();
57             if (co.isExpired() == true) {
58                 values.remove();
59                 count++;
60             }
61         }
62         return count;
63     }
64 }
65
Popular Tags