public class LRUMap<K,V>extends AbstractMap<K,V>implements Cloneable, Serializable
An LRUMap implements a Map of a fixed maximum size that enforces a least recently used discard policy. When the LRUMap is full (i.e., contains the maximum number of entries), any attempt to insert a new entry causes one of the least recently used entries to be discarded.
- The put() method "touches" (or "refreshes") an object, making it "new" again, even if it simply replaces the value for an existing key.
- The get() method also refreshes the retrieved object, but the iterator(), containsValue() and containsKey() methods do not refresh the objects in the cache.
- This implementation is not synchronized. If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. Unlike other Map implementations, even a simple get() operation structurally modifies an LRUMap. Synchronization can be accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap() method. This is best done at creation time, to prevent accidental unsynchronized access to the map:
Map m = Collections.synchronizedMap (new LRUMap (...));
There are other, similar implementations. For instance, see the LRUMap class in the Apache Jakarta Commons Collection API. (This leads to the obvious question: Why write another one? The primary answer is that I did not want to add another third-party library dependency. Plus, I wanted to experiment with this algorithm.)
- See Also:
- Serialized Form