Build an LRU cache with LinkedHashMap
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A cache keeps recent answers close, so an app does not have to fetch them again. Memory is limited, so a cache needs a rule for what to throw away. The most popular rule is LRU: drop the entry that was used longest ago. A LinkedHashMap can do this in a few lines.
What you will learn
- Explain what an LRU cache is and why apps use one
- Turn on access order and use removeEldestEntry to keep a fixed size
- Write a reusable generic LruCache class and count hits and misses
- Cache a slow lookup and measure how many calls it saves
- Build an LRU cache with a HashMap and a doubly linked list
Topics in this lesson
- The idea: least recently used
- A reusable LruCache class
- Caching a slow lookup
- LRU without LinkedHashMap
- Traps: loops and threads
Key points
- An LRU cache removes the entry that was used longest ago when it is full.
new LinkedHashMap<>(16, 0.75f, true)keeps access order; overrideremoveEldestEntryto returnsize() > capacity.- The pattern is
get, on a miss do the slow work, thenput; the hit rate shows how useful the cache is. - Without
LinkedHashMap, use aHashMapplus a doubly linked list;getandputstay O(1).
Interview questions this lesson answers
- What is an LRU cache?
- How do you build an LRU cache with
LinkedHashMap? - What does the third constructor argument of
LinkedHashMapdo? - When is
removeEldestEntrycalled? - How would you build an LRU cache without
LinkedHashMap, and what is the cost? - Is a
LinkedHashMapcache thread-safe? - Follow-up: what is the difference between LRU and LFU?
Sign in to continue this lesson
Create an account to read every lesson, practise with the exercises and keep track of your progress.