KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > cache > FIFOCache


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.Iterator JavaDoc;
7
8 /**
9  * FIFO (first in first out) cache.
10  *
11  * <p>
12  * FIFO (first in first out): just adds items to the cache as they are accessed, putting them in a queue or buffer and
13  * not changing their location in the buffer; when the cache is full, items are ejected in the order they were
14  * added. Cache access overhead is constant time regardless of the size of the cache. The advantage of this algorithm
15  * is that it's simple and fast; it can be implemented using a simple array and an index. The disadvantage is that
16  * it's not very smart; it doesn't make any effort to keep more commonly used items in cache.<br>
17  * Summary for FIFO: fast, not adaptive, not scan resistant
18  */

19 public class FIFOCache extends AbstractCacheMap {
20
21     public FIFOCache(int cacheSize) {
22         this(cacheSize, 0);
23     }
24
25     /**
26      * Creates a new LRU cache.
27      */

28     public FIFOCache(int cacheSize, long timeout) {
29         this.cacheSize = cacheSize;
30         this.timeout = timeout;
31         cacheMap = new LinkedHashMap JavaDoc(cacheSize + 1, 1.0f, false);
32     }
33
34
35     // ---------------------------------------------------------------- prune
36

37     /**
38      * Prune expired objects and, if cache is still full, the first one.
39      */

40     public synchronized int prune() {
41         int count = 0;
42         CacheObject first = null;
43         Iterator JavaDoc values = cacheMap.values().iterator();
44         while (values.hasNext()) {
45             CacheObject co = (CacheObject) values.next();
46             if (co.isExpired() == true) {
47                 values.remove();
48                 count++;
49             }
50             if (first == null) {
51                 first = co;
52             }
53         }
54         if (isFull()) {
55             if (first != null) {
56                 cacheMap.remove(first.key);
57             }
58         }
59         return count;
60     }
61 }
62
Popular Tags