1 package org.apache.turbine.util;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 import org.apache.commons.collections.SequencedHashMap;
20
21 /***
22 * A fixed length object cache implementing the LRU algorithm. Convenient for
23 * buffering recently used objects.
24 *
25 * @author <a href="mailto:dlr@collab.net">Daniel Rall</a>
26 * @author <a href="mailto:hps@intermeta.de">Henning P. Schmiedehausen</a>
27 * @version $Id: BufferCache.java 278822 2005-09-05 19:53:05Z henning $
28 */
29 public class BufferCache
30 extends SequencedHashMap
31 {
32 /*** Serial Version UID */
33 private static final long serialVersionUID = 5206274963401520445L;
34
35 /***
36 * The default maximum cache size.
37 */
38 private static final int DEFAULT_MAX_SIZE = 35;
39
40 /***
41 * The size of the cache. The newest elements in the sequence are kept
42 * toward the end.
43 */
44 private int maxSize;
45
46 /***
47 * Creates a new instance with default storage buffer pre-allocated.
48 */
49 public BufferCache()
50 {
51 this(DEFAULT_MAX_SIZE);
52 }
53
54 /***
55 * Creates a new instance with the specified storage buffer pre-allocated.
56 *
57 * @param maxSize The maximum size of the cache.
58 */
59 public BufferCache(int maxSize)
60 {
61 super(maxSize);
62 this.maxSize = maxSize;
63 }
64
65 /***
66 * Stores the provided key/value pair, freshening its list index if the
67 * specified key already exists.
68 *
69 * @param key The key to the provided value.
70 * @param value The value to store.
71 * @return The previous value for the specified key, or
72 * <code>null</code> if none.
73 */
74 public synchronized Object put(Object key, Object value)
75 {
76 int size = size();
77 if (size > 0 && size + 1 >= maxSize)
78 {
79
80
81 remove(0);
82 }
83 return super.put(key, value);
84 }
85
86 /***
87 * Retrieves the value associated with the provided key, freshening the
88 * sequence of the key as well.
89 *
90 * @param key The key whose value to retrieve.
91 * @return The keyed value.
92 */
93 public synchronized Object get(Object key)
94 {
95 return super.get(key);
96 }
97 }