/Users/lyon/j4p/src/classUtils/pack/util/Cache.java

1    package classUtils.pack.util; 
2     
3    import java.util.HashMap; 
4    import java.util.LinkedList; 
5    import java.util.List; 
6     
7     
8     
9    /** 
10    * A simple cache object, which holds at most <i>n</i> references. 
11    * 
12    * @author Cristiano Sadun 
13    */ 
14   public class Cache { 
15    
16       private HashMap map; 
17    
18       /** 
19        * List of keys, in last-accessed order (first element is the oldest) 
20        */ 
21       private List accessList; 
22       private int max; 
23    
24       /** 
25        * Constructor for Cache. 
26        * @param max the maximum number of references to hold. 
27        */ 
28       public Cache(int max) { 
29           if (max<2) throw new IllegalArgumentException("A cache can't be less than size 2"); 
30           this.max=max; 
31           clear(); 
32       } 
33    
34       /** 
35        * Put an object in the cache. If the cache size exceed the maximum size, 
36        * the least accessed object will be removed. 
37        * 
38        * @param  key of the object to put. 
39        * @return the object just inserted. 
40        */ 
41       public synchronized Object put(Object key, Object value) { 
42           if (map.size() > max) { 
43               if (! (accessList.size() > 0)) throw new IllegalStateException("AccessList size is 0"); 
44               // Remove the first element in the access List 
45               Object obj = accessList.get(0); 
46               accessList.remove(0); 
47               map.remove(obj); 
48           } 
49    
50           // Add the key to the access list, on top 
51           accessList.remove(key); 
52           accessList.add(key); 
53    
54           return map.put(key, value); 
55       } 
56    
57       /** 
58        * Remove an object from the cache. 
59        * 
60        * @param key of the object to remove. 
61        * @return null or the object corresponding to the key. 
62        */ 
63       public synchronized Object remove(Object key) { 
64           Object obj; 
65           if ((obj=map.remove(key))==null) return null; 
66           accessList.remove(key); 
67           return obj; 
68       } 
69    
70       /** 
71        * Find an object into the cache. 
72        * 
73        * @param key the key of the object to get. 
74        * @return null or the object corresponding to the key. 
75        */ 
76       public synchronized Object get(Object key) { 
77           Object obj; 
78           if ((obj=map.get(key))==null) return null; 
79    
80           // Add the key to the access list, on top 
81           accessList.remove(key); 
82           accessList.add(key); 
83    
84           return obj; 
85       } 
86    
87       /** 
88        * Clear the cache. 
89        */ 
90       private void clear() { 
91           map=new HashMap(); 
92           accessList=new LinkedList(); 
93       } 
94    
95   } 
96