Java Design Program · CD22
LRU Cache with Expiry (TTL) in Java
An OTP should vanish after a minute, even if it is used a lot. Adding a time-to-live to an LRU cache removes entries that are too old, not just ones that are unpopular.
Problem Statement
Design a cache with a fixed capacity and put(key, value, ttlMs, now) and get(key, now). A get returns null if the key is missing or its time to live has passed.
When the cache is over capacity, evict the least recently used entry. The current time is passed in so the behaviour can be tested exactly.
Input/Output Examples
put("otp", ttl 1 s) at 0; get at 0.5 sOutput4821Explanation: the entry is still valid.get("otp") at 2 sOutputnullExplanation: it expired at 1 s and is removed.capacity 2: session, cart, then themeOutputsession is evictedExplanation: it was used longest ago.Visual Explanation
- t=0cacheotp → 1000sessioneach entry stores expiresAt
- t=2000get(otp)2000 ≥ 1000remove it null
- t=2200cachesessioncartthemeover capacity
- Evict LRUcachecartthemesession removed
- Donesize = 2
null. When a put pushes the cache over capacity, the least recently used entry (amber) is evicted.Expiry here is lazy: a stale entry is removed when someone looks it up, or when it becomes the least recently used one.
Approaches
Both approaches pass the same 5,000 random test runs. The first builds on LinkedHashMap; the second writes the linked list by hand.
Approach 1: LinkedHashMap in Access Order (Recommended)
Idea: create new LinkedHashMap<>(16, 0.75f, true) so every get moves a key to the end, and override removeEldestEntry() to cap the size.
- Store a record of the value and
expiresAt = now + ttl. - On get, read the entry; if
now ≥ expiresAt, remove it and returnnull. - Let
removeEldestEntry()drop the least recently used entry when the size exceeds the capacity.
Time: O(1) · Space: O(n). for both get and put; n is the capacity.
Approach 2: HashMap and Doubly Linked List
Idea: map keys to nodes of a doubly linked list with sentinels; the most recently used node sits at the head and the tail is evicted.
- On get, unlink the node; if it has expired, remove it, otherwise move it to the head.
- On put, update or create the node and move it to the head.
- If the map is over capacity, remove the node before the tail sentinel.
Time: O(1) · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: LinkedHashMap in Access Order (Recommended)
Very little code, because the JDK class already maintains the usage order.
import java.util.LinkedHashMap;
import java.util.Map;
public class TtlLinkedHashMap {
// LinkedHashMap in access order handles "least recently used"; each value carries its expiry time
static class TtlLruCache {
private record Item(String value, long expiresAt) { }
private final Map<String, Item> map;
TtlLruCache(int capacity) {
map = new LinkedHashMap<>(16, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<String, Item> eldest) {
return size() > capacity;
}
};
}
// The clock is passed in so the example is exact; real code would use System.currentTimeMillis()
void put(String key, String value, long ttlMs, long now) {
map.put(key, new Item(value, now + ttlMs));
}
String get(String key, long now) {
Item item = map.get(key); // also marks the key as recently used
if (item == null) return null;
if (now >= item.expiresAt()) {
map.remove(key); // lazy expiry: removed when found stale
return null;
}
return item.value();
}
int size() { return map.size(); }
}
public static void main(String[] args) {
TtlLruCache cache = new TtlLruCache(2);
cache.put("otp", "4821", 1000, 0); // expires at t=1000 ms
cache.put("session", "abc", 10_000, 0);
System.out.println("t=500 get(otp) = " + cache.get("otp", 500));
System.out.println("t=2000 get(otp) = " + cache.get("otp", 2000)); // too old
cache.put("cart", "3 items", 10_000, 2100);
cache.put("theme", "dark", 10_000, 2200); // full: evict the least recently used
System.out.println("t=2300 get(session) = " + cache.get("session", 2300));
System.out.println("t=2300 get(cart) = " + cache.get("cart", 2300) + ", get(theme) = " + cache.get("theme", 2300));
System.out.println("size = " + cache.size());
}
}
t=500 get(otp) = 4821 t=2000 get(otp) = null t=2300 get(session) = null t=2300 get(cart) = 3 items, get(theme) = dark size = 2
Time complexity: O(1) · Space complexity: O(n).
Approach 2: HashMap and Doubly Linked List
What interviewers expect when they say "do not use LinkedHashMap".
import java.util.HashMap;
import java.util.Map;
public class TtlManualList {
// HashMap for lookups plus a doubly linked list: most recently used at the head, eviction at the tail
static class TtlLruCache {
private static final class Node {
String key, value;
long expiresAt;
Node prev, next;
}
private final int capacity;
private final Map<String, Node> map = new HashMap<>();
private final Node head = new Node(), tail = new Node(); // sentinels
TtlLruCache(int capacity) {
this.capacity = capacity;
head.next = tail;
tail.prev = head;
}
void put(String key, String value, long ttlMs, long now) {
Node n = map.get(key);
if (n == null) {
n = new Node();
n.key = key;
map.put(key, n);
} else {
unlink(n);
}
n.value = value;
n.expiresAt = now + ttlMs;
addFirst(n);
if (map.size() > capacity) {
Node lru = tail.prev;
unlink(lru);
map.remove(lru.key);
}
}
String get(String key, long now) {
Node n = map.get(key);
if (n == null) return null;
unlink(n);
if (now >= n.expiresAt) {
map.remove(key);
return null;
}
addFirst(n);
return n.value;
}
private void unlink(Node n) { n.prev.next = n.next; n.next.prev = n.prev; }
private void addFirst(Node n) { n.next = head.next; n.prev = head; head.next.prev = n; head.next = n; }
int size() { return map.size(); }
}
public static void main(String[] args) {
TtlLruCache cache = new TtlLruCache(2);
cache.put("otp", "4821", 1000, 0); // expires at t=1000 ms
cache.put("session", "abc", 10_000, 0);
System.out.println("t=500 get(otp) = " + cache.get("otp", 500));
System.out.println("t=2000 get(otp) = " + cache.get("otp", 2000)); // too old
cache.put("cart", "3 items", 10_000, 2100);
cache.put("theme", "dark", 10_000, 2200); // full: evict the least recently used
System.out.println("t=2300 get(session) = " + cache.get("session", 2300));
System.out.println("t=2300 get(cart) = " + cache.get("cart", 2300) + ", get(theme) = " + cache.get("theme", 2300));
System.out.println("size = " + cache.size());
}
}
t=500 get(otp) = 4821 t=2000 get(otp) = null t=2300 get(session) = null t=2300 get(cart) = 3 items, get(theme) = dark size = 2
Time complexity: O(1) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| LinkedHashMap in Access Order | O(1) | O(n) |
| HashMap and Doubly Linked List | O(1) | O(n) |
Every operation is a hash lookup plus a few pointer changes. Memory holds at most capacity entries, each with one extra timestamp.
Interview Tips and Recommended Approach
- Inject the clock. Passing the time in (or a
Clock) makes TTL logic testable without sleeping. - Mention active cleanup. Lazy expiry can keep stale entries; a scheduled sweep or a priority queue of expiry times removes them early.
- Synchronise for threads.
LinkedHashMapis not thread-safe, and even a get changes it in access order. - Know the libraries: Caffeine offers
expireAfterWrite()and size limits ready-made.
Recommended Approach: LinkedHashMap in Access Order
Why: it is short, correct and built on a well-tested JDK class. Write the manual list when the interviewer rules LinkedHashMap out.