Java.Collections.How to make a cache with “invalidation policy” using LinkedHashMap?

✅ Why LinkedHashMap?

LinkedHashMap maintains a linked list of entries:

  • Either in insertion order or
  • Access order (when enabled) — which is perfect for caching.

It also provides a protected method:

protected boolean removeEldestEntry(Map.Entry<K, V> eldest)

You can override this to define your invalidation policy (e.g., max size).


🔧 Example: LRU Cache using LinkedHashMap

import java.util.*;

public class LRUCache<K, V> extends LinkedHashMap<K, V> {
    private final int capacity;

    public LRUCache(int capacity) {
        super(capacity, 0.75f, true); // true = access order
        this.capacity = capacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > capacity; // Evict the oldest (least recently used) entry
    }

    public static void main(String[] args) {
        LRUCache<Integer, String> cache = new LRUCache<>(3);
        cache.put(1, "A");
        cache.put(2, "B");
        cache.put(3, "C");
        cache.get(1); // Access key 1 (makes it most recently used)
        cache.put(4, "D"); // Should evict key 2

        System.out.println(cache); // Output: {3=C, 1=A, 4=D}
    }
}

🔍 How it works:

  • accessOrder = true makes the map reorder entries on each get() or put().
  • When size() > capacity, the eldest entry (least recently used) is automatically removed.
  • No external cleanup logic is needed — the cache manages itself! 🧠

🧠 TL;DR

FeatureWith LinkedHashMap
Keep access ordernew LinkedHashMap(cap, 0.75f, true)
Define eviction policyOverride removeEldestEntry(...)
Auto-eviction (e.g. LRU)✅ Built-in with small subclass
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.