public class LRUHashMap<K,V> extends LinkedHashMap<K,V>
Java makes it very easy to implement LRUHashMap - all its functionality is
already available from
LinkedHashMap, and we just need to
configure that properly.
Note that like HashMap, LRUHashMap is unsynchronized, and the user MUST synchronize the access to it if used from several threads. Moreover, while with HashMap this is only a concern if one of the threads is modifies the map, with LURHashMap every read is a modification (because the LRU order needs to be remembered) so proper synchronization is always necessary.
With the usual synchronization mechanisms available to the user, this unfortunately means that LRUHashMap will probably perform sub-optimally under heavy contention: while one thread uses the hash table (reads or writes), any other thread will be blocked from using it - or even just starting to use it (e.g., calculating the hash function). A more efficient approach would be not to use LinkedHashMap at all, but rather to use a non-locking (as much as possible) thread-safe solution, something along the lines of java.util.concurrent.ConcurrentHashMap (though that particular class does not support the additional LRU semantics, which will need to be added separately using a concurrent linked list or additional storage of timestamps (in an array or inside the entry objects), or whatever).
|Constructor and Description|
Create a new hash map with a bounded size and with least recently used entries removed.
|Modifier and Type||Method and Description|
Return the max size
setMaxSize() allows changing the map's maximal number of elements which was defined at construction time.
clone, containsKey, entrySet, isEmpty, keySet, put, putAll, remove, size, values
finalize, getClass, notify, notifyAll, wait, wait, wait
public LRUHashMap(int maxSize)
maxSize- the maximum size (in number of entries) to which the map can grow before the least recently used entries start being removed.
Integer.MAX_VALUEis allowed, but is less efficient than using
HashMapbecause our class needs to keep track of the use order (via an additional doubly-linked list) which is not used when the map's size is always below the maximum size.
public int getMaxSize()
public void setMaxSize(int maxSize)
Note that if the map is already larger than maxSize, the current implementation does not shrink it (by removing the oldest elements); Rather, the map remains in its current size as new elements are added, and will only start shrinking (until settling again on the give maxSize) if existing elements are explicitly deleted.