LinkedHashMap Access-Order LRU

Bound a cache with LinkedHashMap in access order: get refreshes recency and removeEldestEntry evicts the least recently used key once capacity is exceeded.

JavaResilience

Code

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

public class LruCache {

    public static void main(String[] args) {
        int maxEntries = 3;
        // accessOrder=true:get 也算访问;经典 LRU 淘汰最久未访问的键
        Map<String, Integer> lru = new LinkedHashMap<>(16, 0.75f, true) {
            @Override
            protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) {
                return size() > maxEntries;
            }
        };

        lru.put("a", 1);
        lru.put("b", 2);
        lru.put("c", 3);
        lru.get("a");    // a 变为最新
        lru.put("d", 4); // 超容量:淘汰最久未访问的 b
        System.out.println("keys: " + lru.keySet());
        System.out.println("has b: " + lru.containsKey("b"));
        System.out.println("has a: " + lru.containsKey("a"));
    }
}

Inside the snippet

LinkedHashMap Access-Order LRU is built around the class LruCache and the functions main and removeEldestEntry.

Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.

Using it

The demo output is labeled (keys:, has b:, has a:), so every printed line maps back to its originating operation.

main is the driver: it invokes removeEldestEntry before returning.

Key statements

return size() > maxEntries;

Interactive Tools for This Topic

FAQ

What does LinkedHashMap Access-Order LRU print when run?
Running the file directly is enough — expect labeled output lines such as `keys:`, `has b:`, `has a:`.