Tech Interview RoomStudy guides

Concurrency

Implement a thread-safe in-memory cache with per-entry TTL.

Advanced · 2 min read · Lesson 4 of 5 in Concurrency

Problem

Build put(key, value, ttl), get(key) (returns empty if expired) and remove(key) safe for concurrent use, cleaning up expired entries so memory does not grow forever. A common senior-level exercise testing concurrency and design.

Approach

  • Store entries in a ConcurrentHashMap<K, Entry<V>> where each entry holds the value and its expiry time (from System.nanoTime(), monotonic).
  • Lazy expiry on get: if expired, remove it (conditionally, so a fresh value written concurrently is not deleted) and return empty.
  • Active cleanup: a scheduled task periodically removes expired entries, so keys that are never read again do not leak.
  • Use an injectable clock for testability. Bound the size in production (or use Caffeine, which provides expireAfterWrite, variable expiry and size bounds).
java
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.LongSupplier;

final class TtlCache<K, V> implements AutoCloseable {
    private record Entry<V>(V value, long expiresAtNanos) {
        boolean expired(long now) { return now - expiresAtNanos >= 0; }
    }

    private final ConcurrentHashMap<K, Entry<V>> map = new ConcurrentHashMap<>();
    private final LongSupplier clock;
    private final ScheduledExecutorService cleaner;

    TtlCache(Duration cleanupInterval) { this(cleanupInterval, System::nanoTime); }

    TtlCache(Duration cleanupInterval, LongSupplier clock) {
        this.clock = clock;
        this.cleaner = Executors.newSingleThreadScheduledExecutor(r -> {
            Thread t = new Thread(r, "ttl-cache-cleaner");
            t.setDaemon(true);
            return t;
        });
        long ms = cleanupInterval.toMillis();
        cleaner.scheduleAtFixedRate(this::evictExpired, ms, ms, TimeUnit.MILLISECONDS);
    }

    void put(K key, V value, Duration ttl) {
        map.put(key, new Entry<>(value, clock.getAsLong() + ttl.toNanos()));
    }

    Optional<V> get(K key) {
        Entry<V> e = map.get(key);
        if (e == null) return Optional.empty();
        if (e.expired(clock.getAsLong())) {
            map.remove(key, e);            // remove only this exact entry, not a newer one
            return Optional.empty();
        }
        return Optional.of(e.value());
    }

    void remove(K key) { map.remove(key); }

    int size() { return map.size(); }

    void evictExpired() {
        long now = clock.getAsLong();
        map.entrySet().removeIf(en -> en.getValue().expired(now));   // weakly consistent iteration, safe concurrently
    }

    @Override public void close() { cleaner.shutdownNow(); }

    public static void main(String[] args) {
        long[] fakeNow = {0};
        try (TtlCache<String, String> cache = new TtlCache<>(Duration.ofHours(1), () -> fakeNow[0])) {
            cache.put("session:42", "alice", Duration.ofSeconds(30));
            cache.put("session:43", "bob", Duration.ofSeconds(5));
            fakeNow[0] += Duration.ofSeconds(10).toNanos();           // advance the fake clock
            System.out.println(cache.get("session:42").orElse("expired"));  // alice
            System.out.println(cache.get("session:43").orElse("expired"));  // expired
            cache.evictExpired();
            System.out.println("size = " + cache.size());                   // 1
        }
    }
}

Complexity

put, get, remove: O(1) average. Cleanup: O(n) per sweep; with very large caches, use a time-ordered structure (a DelayQueue or timing wheel of keys) so each sweep touches only expired entries.

Follow-up questions interviewers ask

Try answering each one before you open it.

Why use System.nanoTime() instead of System.currentTimeMillis() for expiry?

currentTimeMillis() is wall-clock time and can jump backwards or forwards (NTP corrections, manual changes, leap-second smearing), which would make entries expire early or live too long. nanoTime() is monotonic and meant for measuring elapsed time; compare with now - expiresAt >= 0 (not now >= expiresAt) to stay correct even if the counter overflows.

How would you prevent a thundering herd when a hot key expires?

Add a loading API (get(key, loader)) that uses map.compute or a per-key CompletableFuture so only one thread loads the value while others wait for the same future (request coalescing), and optionally refresh entries in the background shortly before expiry (refresh-ahead) while still serving the old value. Caffeine's refreshAfterWrite does exactly this.