Java and Spring Level 3 This level · 25 of 56
Medium java spring

How do ThreadLocal, static collections and lingering references cause memory retention?

The 30 second answer

A ThreadLocal value lives as long as its thread, and pool threads never die, so a value I forget to remove stays forever and can even leak into the next request. Static maps and caches without eviction grow without limit, and listeners that are never unregistered keep objects alive. I confirm it with a heap dump and look at what holds the biggest retained size.

Could you say this in an interview?

Thread-local values live as long as the thread does. In a thread pool, threads never die, so a value you forget to remove() stays forever and can leak to the next request. Static maps and caches without eviction grow without limit, and listeners that are never unregistered keep objects alive. I confirm with a heap dump (jcmd <pid> GC.heap_dump) and look at what holds the biggest retained size.

What a lingering reference is. The GC only frees objects that are unreachable from the GC roots, such as thread stacks and static fields. A lingering reference is a strong reference to an object you no longer need, held by something that lives much longer than that object, so the object stays reachable and can never be collected. Most Java memory leaks are this, not a GC bug. The common sources are static fields and static collections, caches without a size limit or expiry, listener and callback lists that are never unregistered, ThreadLocal values on pool threads that live as long as the process, and long-lived sessions or contexts that hold onto request data. In a heap dump, I look at the path from a GC root to the retained objects, because that path names the long-lived holder.

Follow-up: How do you use ThreadLocal safely? (try { tl.set(x); ... } finally { tl.remove(); }, or scoped values in newer Java.)

static final ThreadLocal<String> TENANT = new ThreadLocal<>();

static void handle(String tenantId) {
    TENANT.set(tenantId);
    try {
        process();                 // code deep in the call stack reads TENANT.get()
    } finally {
        TENANT.remove();           // pool threads live on; without this the value leaks to the next request
    }
}

A static collection leak in a search service. In a real search service this pattern usually looks like a static map of parsed or rewritten query trees keyed by the raw query string. Every typo, unique filter combination or session ID in the string becomes a new entry that is never evicted. A static list of query listeners that each request adds to but never removes from fails the same way. The program below shows both leaks and the minimal fix: a size-bounded LRU cache built on LinkedHashMap in access order, which evicts the eldest entry through removeEldestEntry, and removing each listener in a finally block when its request ends.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class StaticCacheLeakDemo {

    static class ParsedQuery {                 // a parsed query tree, a few KB each
        final String text;
        final byte[] tree = new byte[4_000];
        ParsedQuery(String text) { this.text = text; }
    }

    interface QueryListener { void onQuery(String query); }

    // LEAK: static, unbounded, never evicted or removed
    static final Map<String, ParsedQuery> PARSED_CACHE = new HashMap<>();
    static final List<QueryListener> LISTENERS = new ArrayList<>();

    static ParsedQuery searchLeaky(String query) {
        ParsedQuery parsed = PARSED_CACHE.computeIfAbsent(query, ParsedQuery::new);
        LISTENERS.add(q -> { /* metrics for this request */ });   // never removed
        for (QueryListener l : LISTENERS) l.onQuery(query);
        return parsed;
    }

    // FIX: size-bounded LRU cache, and unregister the listener when the request ends
    static final int MAX_ENTRIES = 10_000;
    static final Map<String, ParsedQuery> BOUNDED_CACHE =
            new LinkedHashMap<>(16, 0.75f, true) {          // true = access order
                @Override
                protected boolean removeEldestEntry(Map.Entry<String, ParsedQuery> eldest) {
                    return size() > MAX_ENTRIES;
                }
            };
    static final List<QueryListener> FIXED_LISTENERS = new ArrayList<>();

    static ParsedQuery searchFixed(String query) {
        ParsedQuery parsed;
        synchronized (BOUNDED_CACHE) {                     // LinkedHashMap is not thread-safe
            parsed = BOUNDED_CACHE.computeIfAbsent(query, ParsedQuery::new);
        }
        QueryListener listener = q -> { /* metrics for this request */ };
        FIXED_LISTENERS.add(listener);
        try {
            for (QueryListener l : FIXED_LISTENERS) l.onQuery(query);
            return parsed;
        } finally {
            FIXED_LISTENERS.remove(listener);
        }
    }

    static long usedMb() {
        System.gc();
        Runtime rt = Runtime.getRuntime();
        return (rt.totalMemory() - rt.freeMemory()) / (1024 * 1024);
    }

    public static void main(String[] args) {
        for (int i = 0; i < 50_000; i++) searchLeaky("red shoes " + i);
        System.out.println("leaky: cache=" + PARSED_CACHE.size()
                + " listeners=" + LISTENERS.size() + " heap used ~" + usedMb() + " MB");

        PARSED_CACHE.clear();
        LISTENERS.clear();

        for (int i = 0; i < 50_000; i++) searchFixed("red shoes " + i);
        System.out.println("fixed: cache=" + BOUNDED_CACHE.size()
                + " listeners=" + FIXED_LISTENERS.size() + " heap used ~" + usedMb() + " MB");
    }
}

Output on OpenJDK 21. With the heap capped by -Xmx128m, the leaky half fails with an OutOfMemoryError before it finishes.

leaky: cache=50000 listeners=50000 heap used ~200 MB
fixed: cache=10000 listeners=0 heap used ~41 MB

Two points worth saying in the interview. First, the listener list costs CPU as well as memory, because every request loops over every listener ever added, so latency grows with uptime even before memory runs out. Second, in production I would not hand-roll a synchronized LinkedHashMap. The LinkedHashMap Javadoc says it is not synchronized, and one lock around the whole cache becomes a contention point under load. I would use a cache library such as Caffeine, configured with a maximum size and an expiry such as expireAfterWrite.

Alternate interview scenarios

"Your app ran fine for 30 days, then crashed with OutOfMemoryError. No code changes. What happened?"

Thirty days of stable running points to slow growth, not a sudden spike. My hypotheses: a slow leak, such as ThreadLocals in pool threads, a cache or map that never evicts, or listeners that are never removed; data growth, where a query or in-memory list that was small a month ago now loads far more rows; or a rarer path, such as a monthly job or a new kind of input. First I read the error message, because heap space, metaspace and direct buffer memory have different causes. Then I compare heap histograms taken some time apart to see which class keeps growing, and open the heap dump from -XX:+HeapDumpOnOutOfMemoryError to find what is holding those objects. The fix is to remove the reference or bound the structure. A restart only resets the clock.

"Your Spring Boot service works in development but crashes every night at 2 AM in production. How do you debug it?"

A fixed time points to something scheduled, so I first list what runs then: batch jobs, @Scheduled tasks, cron jobs, backups, log rotation or a database maintenance window. Next I find out what "crash" means, because the fixes differ. An OutOfMemoryError in the JVM log is a heap or metaspace problem. A container killed by the kernel or the orchestrator for exceeding its memory limit, with no Java error, means the process total, including native memory, is too large for the limit. A pod restarted by a failing liveness probe means the app was alive but slow, often because every thread waited. Then I use the evidence. Heap after GC rising steadily over the run suggests retention: an unbounded static cache, ThreadLocals in pool threads, or a job that loads everything into memory. GC logs with -Xlog:gc, a heap dump from -XX:+HeapDumpOnOutOfMemoryError and class histograms show what is held. If the job keeps database connections, HikariCP's pool, whose maximum size defaults to 10, runs out, and other requests wait up to connectionTimeout and then fail with an SQLException. That is a timeout, not a crash. leakDetectionThreshold logs where a connection was borrowed but not returned, and try-with-resources fixes it. Finally I alert on heap after GC, pool pending threads and job duration before the failure, and I reproduce the job's data volume outside production.

Sources (7)
  1. LinkedHashMap Javadoc: access order and removeEldestEntry (Java 21)docs.oracle.com
  2. Caffeine wiki: Eviction (size-based and time-based)github.com
  3. ThreadLocal Javadocdocs.oracle.com
  4. Troubleshooting memory leaks (Java 21)docs.oracle.com
  5. jcmddocs.oracle.com
  6. Java 21 java command: -XX:+HeapDumpOnOutOfMemoryError and -Xlog:gcdocs.oracle.com
  7. HikariCP README: maximumPoolSize, connectionTimeout and leakDetectionThresholdgithub.com
Previous
Next