Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

LinkedHashMap: entry order and an LRU cache

LinkedHashMap in java.util stores key–value mappings. The example demonstrates an LRU cache limited to two entries.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

new LinkedHashMap<K, V>(initialCapacity, loadFactor, accessOrder)
protected boolean removeEldestEntry(Map.Entry<K, V> eldest)

java.util.LinkedHashMap uses insertion order by default and does not sort keys. LinkedHashMap(int,float,boolean) takes initial capacity, load factor, and accessOrder: false selects insertion-order mode; true selects access-order mode, from least to most recently accessed. Capacity is not an entry limit. In Java 21, putFirst and putLast can explicitly move an existing entry to the beginning or end, respectively, even in insertion-order mode.

A successful get in access-order mode moves the entry last; containsKey does not reorder. This enables an “LRU access-order cache”: the least recently used entry is evicted.

Override LinkedHashMap.removeEldestEntry, returning size() > limit. After put or putAll inserts a new entry, true evicts the first entry in the current order; the default returns false.

The class is unsynchronized. If multiple threads access the map concurrently and at least one structurally modifies it, external synchronization is required. In access-order mode, even get can count as a structural modification. A safely published insertion-order map can be shared for read-only access without synchronizing each access. Scope: Java SE 21; production runtime is not attested.

Examples

import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> cache =
                new LinkedHashMap<String, Integer>(4, 0.75f, true) {
                    @Override
                    protected boolean removeEldestEntry(
                            Map.Entry<String, Integer> eldest) {
                        return size() > 2;
                    }
                };

        cache.put("A", 1);
        cache.put("B", 2);
        System.out.println(cache.keySet());
        cache.get("A");
        System.out.println(cache.keySet());
        cache.put("C", 3);
        System.out.println(cache);
    }
}

Result

[A, B]
[B, A]
{A=1, C=3}

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources