KatInterview

Debugging a LinkedHashMap-Based Eviction Cache in Java

Data Structure DesignModel answer
MediumModel answerData Structure Designlru-cachejavalinkedhashmap

Last updated

Review a Java cache built on LinkedHashMap that evicts the wrong entries, find each defect, write minimal failing tests, and produce a corrected version.

Review a Faulty Cache Implementation

A teammate opened a pull request adding a fixed-capacity cache that is supposed to discard the least recently used entry when it runs out of room. It is built on java.util.LinkedHashMap. The code compiles in the author's editor, yet the cache throws away the wrong entries in very ordinary usage.

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

public class SimpleLRUCache {
    private final int capacity;
    private final Map cache;

    public SimpleLRUCache(int capacity) {
        if (capacity <= 0) {
            throw new IllegalArgumentException("Capacity must be positive");
        }
        this.capacity = capacity;
        // Intent: LRU eviction, given an initial capacity and the default load factor
        this.cache = new LinkedHashMap(capacity, 0.75f) {
            @Override
            protected boolean removeEldestEntry(Map.Entry eldest) {
                return size() >= capacity;
            }
        };
    }

    public V get(K key) {
        return cache.get(key);
    }

    public void put(K key, V value) {
        cache.put(key, value);
    }

    public int size() {
        return cache.size();
    }
}

(Assume the intended class is generic over key type K and value type V.)

What to deliver

  1. Defects. List every way this code departs from correct LRU behavior, and say why each happens.
  2. Minimal failing tests. For each defect, give a short sequence of put/get calls whose expected result is correct for a proper LRU cache but wrong for this code. Ideally, each test should still fail if only the other defects are fixed.
  3. Fix. Provide a corrected Java implementation.
  4. Why tests matter. Explain briefly why the compiler cannot flag these problems and why scenario-based behavioral tests are needed to protect a cache's invariants.

Hints

Hint 1

Look at which LinkedHashMap constructor is called. What iteration order does the two-argument form give you, and does a read change that order?

Hint 2

Ask when removeEldestEntry is invoked relative to the insertion, and what size() reports at that moment. Then think about what happens when the capacity is 1.

Hint 3

Check the declarations as well: the class and the map use raw types, so the generic signatures do not line up. Then design tests by filling the cache, touching an old key, and inserting one more key.