Quick revision
The short answer
We extend LinkedHashMap, call the constructor super(16, 0.75f, true) so the map keeps entries in access order, and override removeEldestEntry() to return true when size() goes above our capacity. The third argument, accessOrder, is what turns an ordinary insertion-ordered map into an LRU cache. The result is not thread-safe, because even get() changes the internal order.
What to remember
In this answer, we saw that LinkedHashMap keeps a linked list over its entries, and that the constructor argument accessOrder = true makes every get and put move the entry to the tail, so the head is always the least recently used entry. Overriding removeEldestEntry() to return size() > cap evicts that head after each insert. Because even get() changes the list, the class is not thread-safe; a synchronized wrapper makes it correct, and Caffeine is the right choice when many threads share the cache.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We extend LinkedHashMap, call the constructor super(16, 0.75f, true) so the map keeps entries in access order, and override removeEldestEntry() to return true when size() goes above our capacity. The third argument, accessOrder, is what turns an ordinary insertion-ordered map into an LRU cache. The result is not thread-safe, because even get() changes the internal order.
Why this question is asked
An LRU cache, least recently used, keeps a fixed number of entries and throws away the one nobody has touched for the longest time when it needs room. We meet it in real work whenever we keep parsed templates, lookup results or small reference data in memory. Interviewers like this question because the whole answer fits in ten lines of Java, yet it tests whether we know what LinkedHashMap does inside, and whether we notice the concurrency trap hiding in a method that looks read-only. In this answer, we will recap what LinkedHashMap keeps, write the cache, follow a few calls to see the order change, look at how eviction is triggered, and then explain why the cache is not thread-safe and what to use instead.
1A Quick Recap of LinkedHashMap
LinkedHashMap is a HashMap that also remembers an order. Every entry lives in the hash table as usual, so lookups stay fast, but each entry also has two extra pointers, before and after, that link all entries into one doubly linked list. The map keeps a reference to the head of that list, the eldest entry, and to the tail, the youngest one.
By default the list is in insertion order: the order in which keys were first put into the map. Iterating over a LinkedHashMap gives us the keys in that order, which is why people use it when they want predictable iteration. Putting a key that already exists does not move it in insertion order.
LinkedHashMap also supports a second order, access order. In access order, every successful get() or put() on a key moves that key's entry to the tail of the list. The entry at the head is then the one that was used least recently, which is exactly the entry an LRU cache wants to evict.
2Writing the Cache
With that in mind, the cache is a small subclass. We pass three arguments to the parent constructor: the initial capacity of the hash table, the load factor, and accessOrder. Then we override one protected hook.
The first two arguments are the usual HashMap defaults; 16 buckets and a load factor of 0.75 are fine for a small cache. The third argument is the one that matters. With false, or with the shorter constructors, the map stays in insertion order and our class would be a FIFO cache that evicts the oldest inserted key even if it is used all the time.
Notice that get(key) and put(key, value) need no code of our own. LinkedHashMap already moves the entry on access, and the eviction rule is the only behaviour we add.
3Following a Few Calls
Let us create a cache with capacity 2 and watch the list. Printing the map shows the entries from head (least recent) to tail (most recent).
- Find the bucket for the key
hashCode()picks the bucket,equals()finds a matching key - Key already present?Yesreplace the value and move the entry to the tailNocreate a new entry and link it at the tail
- Call removeEldestEntry(head)only after a new entry was inserted
- Hook returned true?Yesunlink and remove the head entryNokeep every entry
4 steps in order. Play them, or step through them one at a time.
get() on an existing key performs only the move to the tail.
The get("a") call looks like a read, but it relinks the entry for a from the head to the tail. When c arrives, the map has three entries, removeEldestEntry() returns true, and the head, which is now b, is removed. If we had built the map with accessOrder false, a would have been evicted instead, even though we had just used it.
4How Eviction Is Triggered
removeEldestEntry() is a hook: LinkedHashMap calls it after every insertion of a new entry, through put(), putAll() and the other methods that add keys, and passes it the current head. The default implementation returns false, so a plain LinkedHashMap never removes anything on its own. When we return true, the map removes the head for us. Updating the value of an existing key is not an insertion, so it does not call the hook, and the size cannot grow that way.
Because we check size() > cap after the insert, the map briefly holds cap + 1 entries and then drops back to cap. That is harmless here. We should not remove entries ourselves inside the hook; the documentation allows it, but then we must return false, and it is easy to get wrong. Returning true and letting the map do the work is the clean form.
5Is It Thread-Safe?
No. LinkedHashMap is not synchronized, and in access order the problem is worse than for a plain HashMap: every get() rewires the before and after pointers of up to three entries. If two threads call get() at the same moment, both may relink the list at once and leave it in a broken state, with entries that point at each other in a loop or entries that fall out of the list. The symptoms are silent wrong evictions, an endless loop during iteration, or a ConcurrentModificationException much later.
The simplest correct fix is to wrap the map: Collections.synchronizedMap(new Lru<>(1000)). Every call then takes one lock, so only one thread touches the list at a time. That is correct but serializes all access, which is fine for low traffic and poor for a hot cache used by many request threads.
For real services, the better answer is a library built for this. Caffeine gives us a concurrent, size-bounded cache with an eviction policy that usually beats plain LRU on hit rate, and Spring's cache abstraction can use it directly.
6Follow-up questions
Why is a ReadWriteLock not enough to protect this map?
A ReadWriteLock lets many readers in at once and only makes writers wait. That works when reads really are reads. In an access-ordered LinkedHashMap, get() is a write to the linked list, because it moves the entry to the tail. If we guard get() with the read lock, several threads relink the list concurrently and corrupt it. We would have to take the write lock for get() as well, and then the ReadWriteLock behaves like a plain exclusive lock with more overhead.
What happens if we pass false as the third argument?
The map keeps insertion order. removeEldestEntry() still evicts the head, but the head is now the key inserted first, so the cache becomes FIFO. A key that is read on every request would still be evicted once enough new keys arrive.
Does iterating over the cache change the order?
Iterating with entrySet() or keySet() does not count as an access, so it does not reorder the entries. Calling get() for each key inside the loop does, and in access order that throws ConcurrentModificationException because the structure changes while we iterate.
7Conclusion
In this answer, we saw that LinkedHashMap keeps a linked list over its entries, and that the constructor argument accessOrder = true makes every get and put move the entry to the tail, so the head is always the least recently used entry. Overriding removeEldestEntry() to return size() > cap evicts that head after each insert. Because even get() changes the list, the class is not thread-safe; a synchronized wrapper makes it correct, and Caffeine is the right choice when many threads share the cache.
Open with
I would extend LinkedHashMap and call super with 16, 0.75f and true. The third argument is accessOrder. With true, every get or put moves the entry to the end of the internal linked list, so the entry at the head is always the least recently used one.
Then, if they want more
Then I override removeEldestEntry, which LinkedHashMap calls after every insertion of a new key with the current head, and return size() greater than the capacity. When it returns true, the map removes the head for me, so get and put need no extra code.
If I forget the true argument, the map stays in insertion order and I get a FIFO cache instead of LRU. On thread safety, the answer is no, and the reason is subtle: in access order even get modifies the structure, because it relinks the entry. Two threads calling get at the same time can corrupt the list.
That is also why a ReadWriteLock does not help, since get would need the write lock anyway. For a small, low-traffic cache I would wrap it with Collections.synchronizedMap. For anything shared by many request threads, I would use Caffeine with maximumSize, which is concurrent and usually gets a better hit rate than plain LRU.
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 official documentation for the version you use. 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 an LRU cache in Java with get(key) and put(key, value) and a fixed capacity...": https://scrivio-interview-library.netlify.app/java/coding-problems/a856893633/