Forgotten feature of LinkedHashMap.

Overview

LinkedHashMap has a couple of nice features. To me the most under-utilised feature as a simple cache with FIFO or LRU eviction policy.

LRU Cache

A cache which evicts the Least-Recently-Used entry is useful for efficiently caching the most used entries.

Map<Key, Value> cache = new LinkedHashMap<Key, Value>(16, 0.7f, true) {
    private static final int MAX_ENTRIES = 100;

    protected boolean removeEldestEntry(Map.Entry<Key, Value> eldest) {
        return size() > MAX_ENTRIES;
    }
};

This use of the constructor tell the LHM to order entries by last access.

FIFO cache

An alternative is to evict the oldest entries.

Map<Key, Value> cache = new LinkedHashMap<Key, Value>() {
    private static final int MAX_ENTRIES = 100;

    protected boolean removeEldestEntry(Map.Entry<Key, Value> eldest) {
        return size() > MAX_ENTRIES;
    }
};

The default behaviour of the LHM to order entries in the order added.

Comments

Popular posts from this blog

Java is Very Fast, If You Don’t Create Many Objects

Hands-On Career: The Evolution of a Java Champion

System wide unique nanosecond timestamps