Eviction policies: LRU and TTL
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's product cache is a plain HashMap, and after a few days the server runs out of memory. A cache needs a size limit and a rule for what to throw away when it is full.
Your turn: the cache is full
The ShopLite cache holds at most 1,000 entries and entry 1,001 arrives. Before reading on, design the rule yourself and write it down. Nothing is graded.
- Which of the 1,000 entries would you remove, and why is that the one least likely to be needed again?
- How would you find that entry fast? What must
getandputcost when the cache holds a million entries? - Entries can also be old without the cache being full. Should those leave too, and what decides it?
Why caches need eviction
Eviction is removing entries from a full cache to make room for new ones. The eviction policy decides which entry goes.
The program below keeps adding products to a plain HashMap used as a cache and prints how big it grows.
Example 1 · An unbounded cache keeps growing
import java.util.HashMap;import java.util.LinkedHashMap;import java.util.Map;
public class WhyEvictDemo { static final int BYTES_PER_ENTRY = 2_000; // a cached search result page, roughly static final int MAX_ENTRIES = 5_000;
public static void main(String[] args) { Map<String, String> unbounded = new HashMap<>(); Map<String, String> bounded = new LinkedHashMap<>(16, 0.75f, true) { @Override protected boolean removeEldestEntry(Map.Entry<String, String> eldest) { return size() > MAX_ENTRIES; } };
for (int day = 1; day <= 5; day++) { for (int i = 0; i < 40_000; i++) { // 40,000 different searches a day String query = "search:day" + day + ":q" + i; unbounded.put(query, "results"); bounded.put(query, "results"); } System.out.printf("Day %d: unbounded %6d entries (~%3d MB), bounded %d entries (~%d MB)%n", day, unbounded.size(), unbounded.size() * (long) BYTES_PER_ENTRY / 1_000_000, bounded.size(), bounded.size() * (long) BYTES_PER_ENTRY / 1_000_000); } }}Day 1: unbounded 40000 entries (~ 80 MB), bounded 5000 entries (~10 MB) Day 2: unbounded 80000 entries (~160 MB), bounded 5000 entries (~10 MB) Day 3: unbounded 120000 entries (~240 MB), bounded 5000 entries (~10 MB) Day 4: unbounded 160000 entries (~320 MB), bounded 5000 entries (~10 MB) Day 5: unbounded 200000 entries (~400 MB), bounded 5000 entries (~10 MB)
What this code does
- Every new search adds an entry to the plain
HashMap. After five days it holds 200,000 results, about 400 MB at 2 KB each, and it never shrinks. - The bounded map evicts once it passes 5,000 entries, so it stays at about 10 MB however long the server runs. Its code is the
LinkedHashMaptrick from the next sections.
A HashMap used as a cache only grows: every new product, search or user adds an entry and nothing ever leaves. Sooner or later the server runs out of heap and crashes with OutOfMemoryError.
A bounded cache has a maximum size. When it is full, it must evict something. The goal is to evict the entry least likely to be needed again, so the hot data stays and the hit ratio stays high.
LRU, LFU and FIFO compared
LRU (least recently used) is an eviction policy that removes the entry that has not been used for the longest time.
The program replays the same accesses through a FIFO, an LRU and an LFU cache of size 3 and prints which entry each one evicts.
Example 2 · FIFO, LRU and LFU on the same accesses
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
public class PolicyCompareDemo { static final int CAPACITY = 3;
// Runs one policy. The list holds the cached keys; which one is removed depends on the policy. static void run(String policy, String[] accesses) { List<String> keys = new ArrayList<>(); // FIFO: insertion order, LRU: recency order Map<String, Integer> uses = new HashMap<>(); // LFU: how often each key was used List<String> evicted = new ArrayList<>(); int hits = 0; for (String k : accesses) { if (keys.contains(k)) { hits++; uses.merge(k, 1, Integer::sum); if (policy.equals("LRU")) { keys.remove(k); keys.add(k); } continue; } if (keys.size() == CAPACITY) { String victim = keys.get(0); if (policy.equals("LFU")) { for (String c : keys) { if (uses.get(c) < uses.get(victim)) { victim = c; } } } keys.remove(victim); uses.remove(victim); evicted.add(victim); } keys.add(k); uses.put(k, 1); } System.out.printf("%-4s hits=%d evicted=%s final=%s%n", policy, hits, evicted, keys); }
static void compare(String title, String... accesses) { System.out.println(title + ": " + String.join(" ", accesses)); run("FIFO", accesses); run("LRU", accesses); run("LFU", accesses); }
public static void main(String[] args) { compare("Sequence 1", "A", "B", "A", "C", "A", "D", "B", "A", "E", "A", "B", "A"); compare("Sequence 2", "A", "A", "B", "A", "C", "D", "E", "A", "B", "C", "A", "D"); }}Sequence 1: A B A C A D B A E A B A FIFO hits=5 evicted=[A, B, C, D] final=[A, E, B] LRU hits=6 evicted=[B, C, D] final=[E, B, A] LFU hits=6 evicted=[B, C, D] final=[A, B, E] Sequence 2: A A B A C D E A B C A D FIFO hits=3 evicted=[A, B, C, D, E, A] final=[B, C, D] LRU hits=3 evicted=[B, A, C, D, E, B] final=[C, A, D] LFU hits=4 evicted=[B, C, D, E, B] final=[A, C, D]
What this code does
- In sequence 1, FIFO evicts the popular
Afirst just because it arrived first, so it gets one hit fewer than LRU and LFU. - In sequence 2, a burst of new pages (
C D E) pushesAout of LRU, while LFU keeps it because it was used three times. No policy wins every pattern; LRU is a good default.
Three classic policies decide who leaves a full cache:
- FIFO (first in, first out): evict the entry added earliest, even if it is used all the time.
- LRU: recent use predicts the next use, so it adapts when the hot data changes.
- LFU (least frequently used): evict the entry used the fewest times. Good for steady favourites, but an old favourite can stay long after people stop reading it.
Trace the code
Trace an LRU cache of size 3
Step through the accesses A B A C D and watch the order of the keys.
Variables
- k
- A
- keys
- []
Output
(nothing printed yet)Line 7Next access: key A.
LRU with LinkedHashMap
removeEldestEntry is a LinkedHashMap method that put calls after adding an entry; when it returns true, the map removes its eldest entry.
LinkedHashMap can keep its entries in access order. The program below builds an LRU cache of capacity 3 from it.
Example 3 · LRU cache with LinkedHashMap
import java.util.LinkedHashMap;import java.util.Map;
class LruCache<K, V> extends LinkedHashMap<K, V> { private final int capacity;
LruCache(int capacity) { super(16, 0.75f, true); // true = access order: get() moves a key to the end this.capacity = capacity; }
@Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { boolean evict = size() > capacity; // called after every put if (evict) { System.out.println(" evict " + eldest.getKey()); } return evict; }}
public class LinkedHashMapLruDemo { public static void main(String[] args) { LruCache<String, Integer> prices = new LruCache<>(3); prices.put("MOB-RN13", 17999); prices.put("MOB-GM35", 19999); prices.put("MOB-IP15", 69900); System.out.println("full: " + prices.keySet());
prices.get("MOB-RN13"); // used again: now the most recent System.out.println("after get: " + prices.keySet());
prices.put("LAP-IPS3", 42990); System.out.println("after put: " + prices.keySet()); }}full: [MOB-RN13, MOB-GM35, MOB-IP15] after get: [MOB-GM35, MOB-IP15, MOB-RN13] evict MOB-GM35 after put: [MOB-IP15, MOB-RN13, LAP-IPS3]
What this code does
get("MOB-RN13")moves it to the end of the order, soMOB-GM35becomes the least recently used.- The fourth
putmakessize()4,removeEldestEntryreturnstrueand the map removesMOB-GM35.
Example 4 · Mistake: forgetting accessOrder = true
import java.util.LinkedHashMap;import java.util.Map;
public class InsertionOrderMistake { static Map<String, String> cache(boolean accessOrder) { return new LinkedHashMap<>(16, 0.75f, accessOrder) { @Override protected boolean removeEldestEntry(Map.Entry<String, String> eldest) { return size() > 2; } }; }
static void run(String label, Map<String, String> c) { c.put("home:deals", "..."); c.put("product:4", "..."); c.get("home:deals"); // the popular key is read again c.put("product:9", "..."); // cache is full: someone must go System.out.println(label + c.keySet()); }
public static void main(String[] args) { run("new LinkedHashMap<>() -> ", cache(false)); // insertion order = FIFO run("accessOrder = true (real LRU) -> ", cache(true)); }}new LinkedHashMap<>() -> [product:4, product:9] accessOrder = true (real LRU) -> [home:deals, product:9]
What this code does
- With the default insertion order, reading
home:dealsdoes not move it, so the popular key is evicted: the cache is FIFO, not LRU. - With
accessOrder = truethe read moves it to the end andproduct:4is evicted instead.
The constructor new LinkedHashMap<>(16, 0.75f, true) has a third argument, accessOrder = true. It makes every get and put move that entry to the end, so the first entry is always the least recently used. Return true from removeEldestEntry when size() > capacity and the map removes that eldest entry. That is a complete LRU cache in about ten lines.
It is not thread-safe: wrap it with Collections.synchronizedMap, or use a library such as Caffeine when several threads share it.
Find the bug
Find the LRU bug
Each cache should hold 3 entries and evict the least recently used. Tap the wrong line.
Reading a product does not protect it from eviction.
Round 1 of 2LRU from scratch: HashMap plus doubly linked list
A doubly linked list is a chain of nodes where each node knows its previous and next node, so a node can be unlinked in O(1) time.
Interviewers often ask for LRU without LinkedHashMap, with O(1) get and put. The picture shows the two structures; the program builds them.
Example 5 · LRU from scratch with O(1) get and put
import java.util.HashMap;import java.util.Map;import java.util.StringJoiner;
class ScratchLru<K, V> { private class Node { K key; V value; Node prev; Node next;
Node(K key, V value) { this.key = key; this.value = value; } }
private final int capacity; private final Map<K, Node> index = new HashMap<>(); // key -> node, O(1) lookup private final Node head = new Node(null, null); // dummy: most recent side private final Node tail = new Node(null, null); // dummy: least recent side
ScratchLru(int capacity) { this.capacity = capacity; head.next = tail; tail.prev = head; }
V get(K key) { Node n = index.get(key); if (n == null) { return null; } unlink(n); addFront(n); return n.value; }
void put(K key, V value) { Node n = index.get(key); if (n != null) { n.value = value; unlink(n); addFront(n); return; } if (index.size() == capacity) { Node lru = tail.prev; unlink(lru); index.remove(lru.key); System.out.println(" evict " + lru.key); } n = new Node(key, value); addFront(n); index.put(key, n); }
private void unlink(Node n) { n.prev.next = n.next; n.next.prev = n.prev; }
private void addFront(Node n) { n.next = head.next; n.prev = head; head.next.prev = n; head.next = n; }
@Override public String toString() { StringJoiner j = new StringJoiner(" <-> ", "[most recent] ", " [least recent]"); for (Node n = head.next; n != tail; n = n.next) { j.add(String.valueOf(n.key)); } return j.toString(); }}
public class ScratchLruDemo { public static void main(String[] args) { ScratchLru<Integer, String> cache = new ScratchLru<>(3); cache.put(1, "Redmi Note 13 5G"); cache.put(2, "Samsung Galaxy M35"); cache.put(3, "iPhone 15 128GB"); System.out.println(cache);
System.out.println("get(1) = " + cache.get(1)); System.out.println(cache);
cache.put(4, "Lenovo IdeaPad Slim 3"); System.out.println(cache); System.out.println("get(2) = " + cache.get(2)); }}[most recent] 3 <-> 2 <-> 1 [least recent] get(1) = Redmi Note 13 5G [most recent] 1 <-> 3 <-> 2 [least recent] evict 2 [most recent] 4 <-> 1 <-> 3 [least recent] get(2) = null
What this code does
indexmaps each key to its node; the list fromheadtotailis the recency order printed bytoString.get(1)moves node 1 to the front. Whenput(4)finds the cache full,tail.prev(node 2) is unlinked and removed from the map, soget(2)returnsnull.
O(1) means constant time: the cost does not grow with the size of the cache. The list keeps keys in recency order, most recent next to head and least recent next to tail. A HashMap<K, Node> finds a key's node in O(1).
On get, look up the node, unlink it and add it at the front. On put into a full cache, remove tail.prev from the list and from the map. Dummy head and tail nodes mean you never check for null at the ends.
Order of execution
Put into a full cache
Put the steps of put for a new key, when the cache is full, in order.
Combining an LRU size limit with TTL
Size and age are two different reasons to remove an entry. The program below combines both and prints every eviction with its reason.
Example 6 · LRU and TTL together, printing every eviction
import java.util.LinkedHashMap;import java.util.Map;
class LruTtlCache<K, V> { private record Item<V>(V value, long expiresAt) { }
private final long ttl; private long now = 0; // fake clock in seconds private final Map<K, Item<V>> map;
LruTtlCache(int capacity, long ttl) { this.ttl = ttl; this.map = new LinkedHashMap<>(16, 0.75f, true) { @Override protected boolean removeEldestEntry(Map.Entry<K, Item<V>> eldest) { if (size() > capacity) { System.out.println(" t=" + now + " evict " + eldest.getKey() + " (size limit)"); return true; } return false; } }; }
void tick(long seconds) { now += seconds; }
V get(K key) { Item<V> item = map.get(key); if (item == null) { return null; } if (now >= item.expiresAt()) { map.remove(key); System.out.println(" t=" + now + " evict " + key + " (expired)"); return null; } return item.value(); }
void put(K key, V value) { map.put(key, new Item<>(value, now + ttl)); }
@Override public String toString() { return "t=" + now + " cache " + map.keySet(); }}
public class LruTtlDemo { public static void main(String[] args) { LruTtlCache<String, String> cache = new LruTtlCache<>(3, 30); // 3 entries, 30 s TTL cache.put("product:1", "Redmi Note 13 5G"); cache.tick(5); cache.put("product:6", "boAt Airdopes 141"); cache.tick(5); cache.put("product:9", "Clean Code"); System.out.println(cache);
cache.tick(5); cache.get("product:1"); // product:1 is now the most recent cache.put("product:12", "Cotton Kurta"); System.out.println(cache);
cache.tick(20); System.out.println("get product:1 -> " + cache.get("product:1")); System.out.println("get product:9 -> " + cache.get("product:9")); System.out.println(cache); }}t=10 cache [product:1, product:6, product:9] t=15 evict product:6 (size limit) t=15 cache [product:9, product:1, product:12] t=35 evict product:1 (expired) get product:1 -> null get product:9 -> Clean Code t=35 cache [product:12, product:9]
What this code does
- At t=15 s the cache is over its size of 3.
product:1was just read, so the least recently used isproduct:6: a size eviction. - At t=35 s
product:1is 35 s old with a 30 s TTL, sogetremoves it as expired.product:9, stored at t=10 s, is still fresh.
LRU removes the least recently used entry when the cache is full. TTL removes an entry that is too old, even when there is plenty of room, so it cannot stay stale forever.
Real caches use both. Store each value with expiresAt, check it on get, and let the LRU rule handle the size. Counting evictions by reason shows whether the cache is too small (many size evictions) or the TTL too short (many expirations).
Next step
Check your understanding
12 quick questions