A small product lookup cache can avoid repeating work, but an ordinary map keeps growing as new product IDs arrive. A capacity limit answers how many entries to retain. A least-recently-used policy answers which entry to remove when the next product arrives.

This Java example holds two fictional product descriptions. After loading A and B, it reads A and inserts C. B must leave because A was used more recently. The complete source ZIP includes the cache, a runnable demo, thirteen tests, setup notes and expected output. No service, network request or build dependency is needed.

Compile and run on JDK 17 or later

You need a JDK with both javac and java on PATH. Extract the ZIP, enter its java-lru-cache directory and run:

javac -Xlint:all -d out LruCache.java CacheDemo.java CacheTest.java
java -cp out CacheDemo
java -cp out CacheTest

The demo prints the order from least recently used to most recently used:

Loaded: [A, B]
Read A: Adapter
After C: [A, C]
Read B: MISS
After replacing A: [C, A]
Size: 2

Checks ran with Microsoft OpenJDK 17.0.11 on Windows. This records the test environment; it does not recommend that older patch version for deployment. The compile command writes generated classes into out, while the download contains source only.

Access order is the essential constructor choice

The default LinkedHashMap tracks insertion order. Reading A would not make it newer than B. Its official API documentation also provides an access-order constructor: the final true argument makes successful lookups and writes affect recency. Iteration then gives us the least recently used key first.

Save the following as LruCache.java. The underlying map stays private so callers cannot insert through an unbounded method or change the eviction rule. After a put grows the map past capacity, the first key is removed through its iterator.

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

public final class LruCache<K, V> {
    private final int capacity;
    private final LinkedHashMap<K, V> entries;

    public LruCache(int capacity) {
        if (capacity < 1) {
            throw new IllegalArgumentException("Capacity must be positive.");
        }

        this.capacity = capacity;
        this.entries = new LinkedHashMap<>(16, 0.75f, true);
    }

    public Optional<V> get(K key) {
        Objects.requireNonNull(key, "key");
        V value = entries.get(key);

        return Optional.ofNullable(value);
    }

    public void put(K key, V value) {
        Objects.requireNonNull(key, "key");
        Objects.requireNonNull(value, "value");

        entries.put(key, value);

        if (entries.size() > capacity) {
            Iterator<K> oldest = entries.keySet().iterator();
            oldest.next();
            oldest.remove();
        }
    }

    public boolean containsKey(K key) {
        Objects.requireNonNull(key, "key");

        return entries.containsKey(key);
    }

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

    public List<K> keysOldestFirst() {
        List<K> snapshot = List.copyOf(entries.keySet());

        return snapshot;
    }
}

The wrapper deliberately defines a small contract. A successful get counts as use; containsKey is a presence check that leaves recency alone. Replacing a value through put counts as use without adding a second copy of the key. A missed lookup leaves the existing order unchanged.

Null keys and values are rejected before mutation. That means an empty Optional represents a miss without ambiguity. Although LinkedHashMap itself permits nulls, the wrapper narrows that behavior. The Map contract permits implementations to restrict keys and values and cautions against mutable keys whose equality changes while stored. Use stable IDs such as strings for this example.

Watch a read change the next eviction

Save this complete runner as CacheDemo.java. The intermediate key snapshots make the policy visible instead of merely checking the final size.

public final class CacheDemo {
    public static void main(String[] args) {
        LruCache<String, String> cache = new LruCache<>(2);
        cache.put("A", "Adapter");
        cache.put("B", "Battery");
        System.out.println("Loaded: " + cache.keysOldestFirst());

        String first = cache.get("A").orElse("MISS");
        System.out.println("Read A: " + first);
        cache.put("C", "Cable");

        System.out.println("After C: " + cache.keysOldestFirst());
        String evicted = cache.get("B").orElse("MISS");
        System.out.println("Read B: " + evicted);

        cache.put("A", "USB adapter");
        System.out.println("After replacing A: " + cache.keysOldestFirst());
        System.out.println("Size: " + cache.size());
    }
}

After A is read, the order becomes B then A. Inserting C briefly grows the private map to three entries; eviction removes B before put returns, leaving A then C. Replacing A next moves it to the newest end, so the output becomes C then A.

keysOldestFirst returns a detached, unmodifiable key list. Inspecting an earlier snapshot does not change after later cache activity. This is a shallow snapshot: mutable key objects are not cloned, and cached values are not deep-copied. The demo uses immutable strings to keep that distinction simple.

Tests that distinguish LRU from insertion order

Save CacheTest.java below. It uses explicit checks that throw AssertionError, so the tests work without the optional -ea runtime flag.

import java.util.List;
import java.util.Objects;

public final class CacheTest {
    private static int passed;

    private static void equal(Object expected, Object actual) {
        if (!Objects.equals(expected, actual)) {
            throw new AssertionError("Expected " + expected + ", got " + actual);
        }
    }

    private static void expect(Class<? extends Throwable> type, Runnable action) {
        try {
            action.run();
        } catch (Throwable error) {
            if (type.isInstance(error)) {
                return;
            }

            throw new AssertionError("Unexpected exception", error);
        }

        throw new AssertionError("Expected " + type.getSimpleName());
    }

    private static void test(String name, Runnable action) {
        action.run();
        passed++;
        System.out.println("PASS " + name);
    }

    private static LruCache<String, Integer> seeded() {
        LruCache<String, Integer> cache = new LruCache<>(2);
        cache.put("A", 1);
        cache.put("B", 2);

        return cache;
    }

    public static void main(String[] args) {
        test("empty cache misses", () -> {
            LruCache<String, Integer> cache = new LruCache<>(2);
            equal(0, cache.size());
            equal(true, cache.get("missing").isEmpty());
        });

        test("zero capacity is rejected", () -> {
            Runnable action = () -> {
                LruCache<String, Integer> invalid = new LruCache<>(0);
            };
            expect(IllegalArgumentException.class, action);
        });

        test("negative capacity is rejected", () -> {
            Runnable action = () -> {
                LruCache<String, Integer> invalid = new LruCache<>(-1);
            };
            expect(IllegalArgumentException.class, action);
        });

        test("new insertion evicts oldest", () -> {
            LruCache<String, Integer> cache = seeded();
            cache.put("C", 3);
            List<String> expected = List.of("B", "C");
            equal(expected, cache.keysOldestFirst());
            equal(false, cache.containsKey("A"));
        });

        test("get refreshes recency before eviction", () -> {
            LruCache<String, Integer> cache = seeded();
            equal(1, cache.get("A").orElseThrow());
            cache.put("C", 3);
            List<String> expected = List.of("A", "C");
            equal(expected, cache.keysOldestFirst());
            equal(false, cache.containsKey("B"));
        });

        test("containsKey does not refresh recency", () -> {
            LruCache<String, Integer> cache = seeded();
            equal(true, cache.containsKey("A"));
            cache.put("C", 3);
            equal(false, cache.containsKey("A"));
        });

        test("missing get does not change order", () -> {
            LruCache<String, Integer> cache = seeded();
            equal(true, cache.get("Z").isEmpty());
            List<String> expected = List.of("A", "B");
            equal(expected, cache.keysOldestFirst());
        });

        test("replacement refreshes recency without growing", () -> {
            LruCache<String, Integer> cache = seeded();
            cache.put("A", 9);
            List<String> expected = List.of("B", "A");
            equal(expected, cache.keysOldestFirst());
            equal(2, cache.size());
            equal(9, cache.get("A").orElseThrow());
        });

        test("capacity one keeps the last entry", () -> {
            LruCache<String, Integer> cache = new LruCache<>(1);
            cache.put("A", 1);
            cache.put("B", 2);
            equal(false, cache.containsKey("A"));
            equal(1, cache.size());
            equal(2, cache.get("B").orElseThrow());
        });

        test("null writes fail before mutating order", () -> {
            LruCache<String, Integer> cache = seeded();
            Runnable nullKey = () -> cache.put(null, 3);
            Runnable nullValue = () -> cache.put("A", null);
            expect(NullPointerException.class, nullKey);
            expect(NullPointerException.class, nullValue);
            List<String> expected = List.of("A", "B");
            equal(expected, cache.keysOldestFirst());
        });

        test("null lookups are rejected", () -> {
            LruCache<String, Integer> cache = seeded();
            Runnable get = () -> cache.get(null);
            Runnable contains = () -> cache.containsKey(null);
            expect(NullPointerException.class, get);
            expect(NullPointerException.class, contains);
        });

        test("key snapshot is detached and unmodifiable", () -> {
            LruCache<String, Integer> cache = seeded();
            List<String> snapshot = cache.keysOldestFirst();
            cache.get("A");
            cache.put("C", 3);
            List<String> expected = List.of("A", "B");
            equal(expected, snapshot);
            Runnable mutation = () -> snapshot.add("Z");
            expect(UnsupportedOperationException.class, mutation);
        });

        test("repeated inserts stay within capacity", () -> {
            LruCache<Integer, Integer> cache = new LruCache<>(3);

            for (int index = 0; index < 100; index++) {
                cache.put(index, index * 2);

                if (cache.size() > 3) {
                    throw new AssertionError("Capacity exceeded");
                }
            }

            List<Integer> expected = List.of(97, 98, 99);
            equal(expected, cache.keysOldestFirst());
        });

        System.out.println(passed + " tests passed.");
    }
}

The original source and a separately extracted ZIP each compiled with -Xlint:all without diagnostics, passed thirteen named tests and printed the exact demo output above. A temporary negative-control copy changed the constructor's access-order argument from true to false. The get-refreshes-recency test failed, demonstrating that the verifier catches a cache that evicts by insertion order instead.

ScenarioChecked behavior
Empty cache and absent keyA miss returns an empty Optional without changing order.
Insertion, successful read and replacementThe appropriate oldest entry is evicted; replacement preserves size.
Presence check and key snapshotsPresence does not refresh use; snapshots are detached and unmodifiable.
Zero/negative capacity and null inputsInvalid calls fail; rejected writes preserve existing order.
Capacity one and 100 repeated insertionsSize remains bounded and the expected final keys survive.

Where this teaching cache stops

The limit counts entries, not bytes. Two unusually large values can consume more memory than many small values. Nothing expires by time, and there is no automatic refresh when the underlying product data changes. A real application must decide how it invalidates stale descriptions or prices rather than treating recency as freshness.

This implementation is single-threaded. Even a get can alter access order, so sharing the instance between request threads without an appropriate synchronization design is unsafe. The example does not implement concurrent loading, stampede prevention, metrics or distributed consistency. Those are reasons to select a production cache appropriate to the application, not to assume this small wrapper supplies them.

If compilation reports that javac is missing, install/configure a JDK rather than only a runtime. If Java cannot find CacheDemo, run from the extracted folder and keep -cp out in the command. After experimenting, the generated out directory can be removed; no application data is written by the example.