Java
Time-Based Cache
Expiring Keys
Programming
Data Structures

Java expiring map and TTL cache with time-based keys

Codemia Knowledge Hub ·

The standard Java collections framework has no map with expiring keys. You can build one yourself (a HashMap for the data plus a PriorityQueue of expiry times), but for production code a library such as Google Guava or Caffeine is the better choice, since both support expirable entries out of the box.

Fixed vs variable expiration

Each key-value pair gets an expiry time, and once it passes the entry is no longer valid and should be removed. There are two common models:

  1. Fixed expiration: every key expires after the same duration.
  2. Variable expiration: the expiry time differs per entry, based on specific conditions or usage patterns.

Lazy vs active removal

  • Lazy expiration: check for and remove expired entries on each access. It is simple, but stale data can linger until something touches the map.
  • Active expiration: a separate thread or scheduler removes expired entries at regular intervals. The map stays mostly up to date at the cost of extra resource overhead.
TechniqueComplexityMemory EfficiencyData FreshnessUse Case
Lazy ExpirationLowMediumLowMinimal resource usage
Active ExpirationHighHighHighHigh freshness requirement

A DIY expiring map with HashMap and PriorityQueue

The HashMap holds the data and the PriorityQueue orders keys by expiration time, so the expired ones are always at the head of the queue and can be removed cheaply:

java
1import java.util.*;
2
3public class ExpiringMap<K, V> {
4    private final long ttl;
5    private final Map<K, Entry<V>> map = new HashMap<>();
6    private final PriorityQueue<ExpiryKey<K>> expiryQueue = new PriorityQueue<>();
7
8    public ExpiringMap(long ttl) {
9        this.ttl = ttl;
10    }
11
12    public void put(K key, V value) {
13        long expiryTime = System.currentTimeMillis() + ttl;
14        map.put(key, new Entry<>(value, expiryTime));
15        expiryQueue.add(new ExpiryKey<>(key, expiryTime));
16    }
17
18    public V get(K key) {
19        removeExpired();
20        Entry<V> entry = map.get(key);
21        return entry == null ? null : entry.value;
22    }
23
24    private void removeExpired() {
25        long currentTime = System.currentTimeMillis();
26        while (!expiryQueue.isEmpty() && expiryQueue.peek().expiryTime <= currentTime) {
27            ExpiryKey<K> expired = expiryQueue.poll();
28            Entry<V> current = map.get(expired.key);
29            // Skip stale queue entries left behind when the key was put again
30            if (current != null && current.expiryTime == expired.expiryTime) {
31                map.remove(expired.key);
32            }
33        }
34    }
35
36    private static class Entry<V> {
37        final V value;
38        final long expiryTime;
39
40        Entry(V value, long expiryTime) {
41            this.value = value;
42            this.expiryTime = expiryTime;
43        }
44    }
45
46    private static class ExpiryKey<K> implements Comparable<ExpiryKey<K>> {
47        final K key;
48        final long expiryTime;
49
50        ExpiryKey(K key, long expiryTime) {
51            this.key = key;
52            this.expiryTime = expiryTime;
53        }
54
55        @Override
56        public int compareTo(ExpiryKey<K> o) {
57            return Long.compare(this.expiryTime, o.expiryTime);
58        }
59    }
60}

This version uses lazy expiration: get purges expired keys before reading. Each map entry remembers its own expiry time, so when a key is put again, the older queue entry for it is recognised as stale and does not remove the fresh value early.

Using Guava's CacheBuilder

Well-tested libraries are generally the safer option. Here is a Guava cache whose entries expire 10 minutes after being written:

java
1import com.google.common.cache.CacheBuilder;
2import java.util.concurrent.TimeUnit;
3
4var cache = CacheBuilder.newBuilder()
5               .expireAfterWrite(10, TimeUnit.MINUTES)
6               .build();

Which approach fits depends on data volume, freshness requirements and available system resources.


Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design