How do you build an LRU cache using LinkedHashMap?
Reviewed by Gurusankar M.
β‘ Short Answer
Construct LinkedHashMap with accessOrder=true (reorders on access) and override removeEldestEntry to evict when size exceeds capacity. It's O(1) get/put with automatic LRU eviction β but not thread-safe, so wrap or use Caffeine in production.
βCoffee Chat Question
Concept Made Simple
βHow do you build an LRU cache using LinkedHashMap?β
π§ Mind Map Answer
Remember It Faster
accessOrder=true moves a touched entry to the tail, so the head is always the least-recently-used. removeEldestEntry returns true to evict it when over capacity.
β¨οΈHands-on Keyboard
Learn by Doing
Map<K,V> lru = new LinkedHashMap<>(16, 0.75f, true) {
protected boolean removeEldestEntry(Map.Entry<K,V> e) {
return size() > MAX;
}
};π₯What If?
Think Beyond the Expected
Why wouldn't you ship this LinkedHashMap LRU to production as-is?
It isn't thread-safe and has no TTL, hit/miss metrics, or weak references. Under concurrency you'd wrap it (and synchronize iteration) or β better β use Caffeine/Guava which give bounded size, TTL, async loading and stats out of the box.
πReal World
LinkedHashMap LRU is a great interview demonstration and fine for small single-threaded caches, but real services use Caffeine for bounded, concurrent, observable caching.
π―Interviewer's Expectation
Keywords they're listening for:
β οΈCommon Mistakes
- βForgetting accessOrder=true (gives insertion-order, not LRU)
- βUsing it concurrently without synchronization
- βReinventing caching instead of using Caffeine
β Best Practices
- βUse Caffeine/Guava for production caches
- βBound every cache (size + TTL)
- βExpose hit-rate metrics
πFollow-up Questions
- 1How would you make it thread-safe?
- 2How does Caffeine's W-TinyLFU differ from pure LRU?
- 3How do you add TTL/expiry?
π§©Related Technologies
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly β AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: HashMap Internals (Java Collections) Interview question: "How do you build an LRU cache using LinkedHashMap?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
β Featured Products
Support our platform by exploring our recommended products.
As an Amazon affiliate, purchases through these links may earn us a small commission β at no extra cost to you. It helps keep Full Stack Interview Guru free.