Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Implement a simple LRU cache that holds at most 100 entries using LinkedHashMap, and explain what each constructor argument and overridden method does.

We create a LinkedHashMap with new LinkedHashMap<>(16, 0.75f, true), where 16 is the initial capacity, 0.75 the load factor and true selects access order, so every get or put moves the entry to the end. We override removeEldestEntry(Map.Entry<K,V> eldest) to return size() > 100; the map calls it after each insertion of a new mapping, and returning true removes the eldest entry, which in access order is the least recently used one. In access-order mode even get() is a structural modification, so the map is not safe for concurrent readers, and wrapping it in Collections.synchronizedMap makes it correct but serializes every read.

Why this question is asked

An LRU cache, least recently used, keeps the entries we touched most recently and throws away the one we have not touched for the longest time when it is full. It is a classic coding question because the JDK already contains almost all of it: LinkedHashMap was designed with exactly this use in mind. Interviewers want to see that we know the constructor argument that turns it on, the hook method that evicts, and the threading caveat that comes with it. In this answer, we will recap how access order works, write the cache, test it step by step, explain each argument and the overridden method, and then deal with concurrency.

1A Quick Recap: Access Order

A LinkedHashMap links all its entries in a doubly linked list. By default the list is in insertion order. If we pass true as the third constructor argument, accessOrder, the list is in access order: every time we read or update an entry, it moves to the end. The front of the list is then always the least recently used entry, which is exactly the one an LRU cache should evict.

2Writing the Cache

We extend LinkedHashMap, pass the access-order flag to its constructor, and override one protected method.

Java
import java.util.LinkedHashMap;
import java.util.Map;
public class LruCache<K, V> extends LinkedHashMap<K, V> {
private final int maxEntries;
public LruCache(int maxEntries) {
super(16, 0.75f, true); // capacity 16, load factor 0.75, access order
this.maxEntries = maxEntries;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > maxEntries; // true -> the map removes eldest
}
}
LruCache<String, String> cache = new LruCache<>(100);

That is the whole cache. Everything else, lookups, ordering and eviction, comes from LinkedHashMap.

3What Each Argument and Method Does

The first constructor argument, 16, is the initial capacity of the hash table, and the second, 0.75f, is the load factor, the fill ratio at which the table doubles. Both are the defaults; we pass them only because the constructor that takes accessOrder requires all three. For a cache of 100 we could pass a capacity of 256 to avoid resizes as it fills, but at this size it hardly matters.

The third argument, true, is the important one. It selects access order, so get(), put() on an existing key, getOrDefault() and the compute methods all move the entry to the end of the list.

removeEldestEntry() is a hook. LinkedHashMap calls it after every insertion of a new mapping, through put(), putAll(), putIfAbsent() or computeIfAbsent(), passing the eldest entry, the one at the front of the list. By default it returns false, so nothing is removed. Our version returns true when the size has gone over 100, and the map then removes that eldest entry. Because the check runs after the insertion, the map briefly holds 101 entries and immediately drops back to 100. Replacing the value of an existing key is not an insertion, so it never triggers eviction.

Step throughWhat put() does in the LRU cache
  1. Key already present?
    YesReplace value, move entry to the endNoAdd new entry at the end
  2. Call removeEldestEntry(eldest)only after a new entry
  3. size() > 100?
    YesRemove the front entry: least recently usedNoKeep everything

3 steps in order. Play them, or step through them one at a time.

4Testing It Step by Step

A small cache makes the behaviour easy to see.

Java
LruCache<String, Integer> c = new LruCache<>(3);
c.put("a", 1); c.put("b", 2); c.put("c", 3);
System.out.println(c); // {a=1, b=2, c=3}
c.get("a"); // a becomes most recently used
System.out.println(c); // {b=2, c=3, a=1}
c.put("d", 4); // size 4 > 3: evict the eldest, b
System.out.println(c); // {c=3, a=1, d=4}
c.put("c", 30); // existing key: no eviction, c moves to the end
System.out.println(c); // {a=1, d=4, c=30}
System.out.println(c.containsKey("a")); // true, and containsKey does not count as an access

Notice that b, not a, was evicted, because the get() on a made it recent. That is the difference between LRU and plain first-in-first-out. Also notice that containsKey() does not move the entry; only reading or writing the value counts as an access.

5The Concurrency Catch

In access-order mode, get() changes the linked list. The Javadoc calls this out: merely querying an access-ordered map with get is a structural modification. So two threads calling get() at the same time can both relink entries and corrupt the list, and a thread iterating the map while another calls get() will see ConcurrentModificationException. Unlike a HashMap, where many readers without writers are safe after safe publication, this map is not safe even for readers alone.

The quick fix is Collections.synchronizedMap(new LruCache<>(100)), which puts one lock around every method. That is correct, but it makes every read wait for every other read, so under load all threads queue on one monitor. For a cache used by many request threads, a concurrent cache library such as Caffeine, with a maximumSize(100) bound, is the better choice; the LinkedHashMap version is ideal for single-threaded code and for small, lightly used caches.

Java
Map<String, String> shared = Collections.synchronizedMap(new LruCache<>(100)); // correct, but one lock
Cache<String, String> better = Caffeine.newBuilder().maximumSize(100).build(); // concurrent reads

6Follow-up questions

How would you make eviction depend on total byte size instead of count?

We keep a running total of the sizes of the values and evict from the front until the total is under the limit. removeEldestEntry can only remove one entry per call by returning true, but the Javadoc allows it to modify the map itself and return false, so we can loop over the eldest entries there. A cleaner way is a small class that wraps the LinkedHashMap, adds each value's weight on put, subtracts it on removal, and then removes entries through the map's iterator from the front while the total is over the budget. In production, Caffeine's maximumWeight with a weigher function does exactly this, concurrently.

Why not override get() to move entries yourself?

Because LinkedHashMap already does it internally and efficiently with afterNodeAccess, and reimplementing it would duplicate logic and risk bugs. The accessOrder flag is the supported way.

Should the cache class extend LinkedHashMap or wrap it?

Extending is shortest and is what the JDK documentation shows. Wrapping, by holding a private LinkedHashMap and exposing only get and put, hides methods such as iteration and putAll that callers should not use and makes it easier to add locking or metrics later.

7Conclusion

In this answer, we built an LRU cache of 100 entries by extending LinkedHashMap with the constructor arguments 16, 0.75f and true, where the last selects access order so that get and put move an entry to the end. We overrode removeEldestEntry to return size() > 100, which the map calls after each new insertion, so the eldest, least recently accessed entry is evicted first. Because get() is a structural modification in access-order mode, the map is not safe for concurrent readers, and Collections.synchronizedMap makes it correct only by serializing every read.

What to say in the interviewAbout 90 seconds aloud

Open with

I would extend LinkedHashMap and call super(16, 0.75f, true). The 16 is the initial capacity and 0.75 the load factor, just the defaults, and the third argument, true, is the important one: it switches the map from insertion order to access order, so every get, or put on an existing key, moves that entry to the end of the internal linked list.

Then, if they want more

The front of the list is then always the least recently used entry. Then I override the protected method removeEldestEntry, which LinkedHashMap calls after every insertion of a new mapping and passes the eldest entry. I return size() > 100.

When that is true, the map removes the eldest entry, so the cache goes to 101 entries for a moment and immediately back to 100, always evicting the least recently accessed key. Updating an existing key does not count as an insertion, so it never evicts.

If I put a, b and c into a cache of three, read a, and then put d, it evicts b, not a, which is what makes it LRU rather than FIFO. The important caveat is threading. In access-order mode even get modifies the linked list, so it is a structural modification, and concurrent readers can corrupt it.

Wrapping it in Collections.synchronizedMap makes it correct, but every read then takes the same lock, so for a busy shared cache I would use Caffeine with maximumSize instead.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Implement a simple LRU cache that holds at most 100 entries using LinkedHashMap, and...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/c6a462fdce/