Skip to lesson

Leaks from listeners, resources and ThreadLocal

Some leaks hide in code that registers, opens or starts something: a listener added to a long-lived object, a connection borrowed from a pool, a value set in a ThreadLocal, a thread pool created per request. Each one needs a matching remove, close or shutdown.

Listeners and callbacks that are never removed

A listener is an object registered with a long-lived source to be called when an event happens. If it is never unregistered, the source keeps it alive for ever.

A listener (or callback) is an object you register with another object so it can call you back when something happens: bus.addListener(screen). The bus now holds a strong reference to the listener.

Example 1 · Screens that keep listening after they close

ListenerLeakDemo.javaJava
import java.util.ArrayList;import java.util.List;
interface ResultListener {    void onResultsPublished(String exam);}
class ResultBus {    // Lives for the whole app, so every listener in it stays reachable.    static final List<ResultListener> listeners = new ArrayList<>();
    static void addListener(ResultListener l) {        listeners.add(l);    }
    static void removeListener(ResultListener l) {        listeners.remove(l);    }
    static void publish(String exam) {        for (ResultListener l : listeners) {            l.onResultsPublished(exam);        }    }}
class ResultScreen implements ResultListener {    final byte[] pageData = new byte[100_000];     // charts, photos, marks table    private final boolean cleansUp;
    ResultScreen(boolean cleansUp) {        this.cleansUp = cleansUp;        ResultBus.addListener(this);    }
    @Override    public void onResultsPublished(String exam) {    }
    void close() {        if (cleansUp) {            ResultBus.removeListener(this);        // the fix        }    }}
public class ListenerLeakDemo {    public static void main(String[] args) {        for (int i = 0; i < 1000; i++) {            new ResultScreen(false).close();        }        System.out.println("Leaky screens still listening: " + ResultBus.listeners.size());
        ResultBus.listeners.clear();        for (int i = 0; i < 1000; i++) {            new ResultScreen(true).close();        }        System.out.println("Fixed screens still listening: " + ResultBus.listeners.size());    }}
Output
Leaky screens still listening: 1000
Fixed screens still listening: 0

What this code does

  • Each ResultScreen registers itself with the static ResultBus. The leaky screens never unregister, so after 1000 open-and-close cycles the bus holds 1000 screens, each with 100 KB of page data that can never be collected.
  • The fixed screen calls removeListener(this) in close(). The bus ends with 0 listeners, and every closed screen is garbage.

If the bus lives long and the listener is never removed, the listener and everything it holds stay reachable after it is no longer used. This is called the lapsed listener problem. It is easy to miss because the listener is usually a "short-lived" thing, a screen, a dialog, a request handler, while the bus, event source or scheduler lives for the whole app. Each open-and-close adds one more object that can never be collected, and each event now also wastes time calling dead listeners. The fix is a clear pairing: whoever calls add also calls remove, in the listener's close() or dispose() method. Some APIs return a subscription object whose close() removes the listener, which lets you use try-with-resources.

Unclosed streams, connections and readers

Streams, readers, sockets and database connections hold resources outside the heap: operating-system file handles, network sockets, slots in a connection pool.

Example 2 · A connection lost on the exception path

ConnectionLeakDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
class Pool {    private final Deque<Conn> free = new ArrayDeque<>();
    Pool(int size) {        for (int i = 1; i <= size; i++) {            free.push(new Conn(this, i));        }    }
    Conn borrow() {        if (free.isEmpty()) {            throw new IllegalStateException("pool exhausted");        }        return free.pop();    }
    void giveBack(Conn c) {        free.push(c);    }
    int available() {        return free.size();    }}
class Conn implements AutoCloseable {    private final Pool pool;    final int id;
    Conn(Pool pool, int id) {        this.pool = pool;        this.id = id;    }
    void update(String roll) {        if (roll.isEmpty()) {            throw new IllegalArgumentException("empty roll number");        }    }
    @Override    public void close() {        pool.giveBack(this);    }}
public class ConnectionLeakDemo {    static void saveLeaky(Pool pool, String roll) {        Conn c = pool.borrow();        c.update(roll);          // throws for a bad roll...        c.close();               // ...so this line is skipped and the connection is lost    }
    static void saveSafe(Pool pool, String roll) {        try (Conn c = pool.borrow()) {            c.update(roll);        }    }
    public static void main(String[] args) {        String[] rolls = {"R1", "", "R2", "", "", "R3"};
        Pool leaky = new Pool(3);        for (String roll : rolls) {            try {                saveLeaky(leaky, roll);            } catch (RuntimeException e) {                System.out.println("leaky: " + e.getMessage() + ", free now " + leaky.available());            }        }
        Pool safe = new Pool(3);        for (String roll : rolls) {            try {                saveSafe(safe, roll);            } catch (RuntimeException e) {                System.out.println("safe:  " + e.getMessage() + ", free now " + safe.available());            }        }    }}
Output
leaky: empty roll number, free now 2
leaky: empty roll number, free now 1
leaky: empty roll number, free now 0
leaky: pool exhausted, free now 0
safe:  empty roll number, free now 3
safe:  empty roll number, free now 3
safe:  empty roll number, free now 3

What this code does

  • saveLeaky calls close() only on the happy path. Each bad roll number throws before close(), so the free count drops 2, 1, 0, and the next good request fails with pool exhausted.
  • saveSafe uses try-with-resources: the connection goes back to the pool even when update throws, so all 3 stay free.

Forgetting close() leaks those, and they usually run out long before memory does: "Too many open files", or a pool that has no free connections. The dangerous path is the exception path. Code like c = pool.borrow(); c.update(x); c.close(); works in every test until update throws; then close() is skipped and the connection is lost for good. A few such errors per hour and, by evening, every request waits for a connection that never comes back. try-with-resources closes the resource on every path: normal end, return and exceptions. For things that are not AutoCloseable, use try { ... } finally { release(); }.

ThreadLocal values in thread pools and why remove() matters

A ThreadLocal gives each thread its own copy of a variable: currentUser.set("asha") is seen only by the thread that set it. The values live inside the Thread object, so they stay as long as the thread lives, unless you call remove().

Example 3 · A ThreadLocal value leaks into the next request

ThreadLocalPoolDemo.javaJava
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;
public class ThreadLocalPoolDemo {    static final ThreadLocal<String> currentUser = new ThreadLocal<>();
    static void handleLeaky(String user) {        if (user != null) {            currentUser.set(user);          // set, but never removed        }        System.out.println("leaky request for " + user + " runs as " + currentUser.get());    }
    static void handleSafe(String user) {        try {            if (user != null) {                currentUser.set(user);            }            System.out.println("safe  request for " + user + " runs as " + currentUser.get());        } finally {            currentUser.remove();           // always clean up before the thread is reused        }    }
    public static void main(String[] args) throws InterruptedException {        ExecutorService pool = Executors.newSingleThreadExecutor();        pool.submit(() -> handleLeaky("asha"));        pool.submit(() -> handleLeaky(null));      // a guest: should run as nobody        pool.submit(() -> handleSafe("ravi"));        pool.submit(() -> handleSafe(null));        pool.shutdown();        pool.awaitTermination(5, TimeUnit.SECONDS);    }}
Output
leaky request for asha runs as asha
leaky request for null runs as asha
safe  request for ravi runs as ravi
safe  request for null runs as null

What this code does

  • The pool has one thread that runs every task. handleLeaky("asha") sets the value and never removes it, so the next request, a guest, runs as asha: memory is held and data leaks to the wrong user.
  • handleSafe removes the value in finally, so the guest after Ravi correctly sees null. The finally runs even if the request throws.

In a thread pool the threads never end: the same thread runs request after request. A value set during one request and not removed is still there for the next one. That is a memory leak (one value per pool thread, which can be large), and often a worse bug: the next request, perhaps a guest's, runs as the previous user. Rule: set in a try, remove() in the finally. In application servers a forgotten ThreadLocal value can even keep a whole undeployed application's classes in memory, because the value's class points to its class loader.

Inside each thread, a ThreadLocal is held weakly but its value strongly (on HotSpot's ThreadLocalMap). Stale values are cleaned only now and then, so never rely on the GC; call remove().

Executor threads that are never shut down

An executor (thread pool) owns threads that wait for work. Executors.newFixedThreadPool(2) creates up to 2 threads that stay alive, idle, until you call shutdown(). These are not daemon threads, so a forgotten executor also stops the JVM from exiting when main ends.

Example 4 · A new thread pool for every report

ExecutorLeakDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;
public class ExecutorLeakDemo {    static final List<ExecutorService> forgotten = new ArrayList<>();   // only so main can clean up
    // BUG: a new pool for every report request, never shut down.    static int reportLeaky(int batch) throws Exception {        ExecutorService pool = Executors.newFixedThreadPool(2);        forgotten.add(pool);        Future<Integer> a = pool.submit(() -> batch * 10);        Future<Integer> b = pool.submit(() -> batch * 20);        return a.get() + b.get();    }
    static long poolThreads() {        return Thread.getAllStackTraces().keySet().stream()                .filter(t -> t.getName().startsWith("pool-"))                .count();    }
    public static void main(String[] args) throws Exception {        for (int batch = 1; batch <= 5; batch++) {            reportLeaky(batch);            System.out.println("After report " + batch + ": live pool threads = " + poolThreads());        }
        // Without this cleanup the JVM would never exit: pool threads are not daemon threads.        for (ExecutorService pool : forgotten) {            pool.shutdown();        }        boolean allDone = true;        for (ExecutorService pool : forgotten) {            allDone &= pool.awaitTermination(5, TimeUnit.SECONDS);        }        System.out.println("After shutdown, all pools terminated: " + allDone);    }}
Output
After report 1: live pool threads = 2
After report 2: live pool threads = 4
After report 3: live pool threads = 6
After report 4: live pool threads = 8
After report 5: live pool threads = 10
After shutdown, all pools terminated: true

What this code does

  • Each call creates a 2-thread pool and returns without shutdown(). The threads wait for work that never comes, so the count grows by 2 per report: 10 threads after 5 reports, and in a server, thousands by evening.
  • The program keeps the pools in a list only so it can shut them down at the end; without that loop the JVM would not exit, because pool threads are non-daemon threads.

Creating a new executor per request and never shutting it down leaks threads: each one has its own stack (about 1 MB reserved by default on 64-bit HotSpot) and its own Thread object, and everything its tasks still reference. Eventually the JVM fails with OutOfMemoryError: unable to create native thread. Create one executor for a job or for the whole application, reuse it, and shut it down when the application stops. Since Java 19, ExecutorService also has close(), so on Java 21 it works in try-with-resources: close() waits for submitted tasks and then shuts the pool down.

Next step

Check your understanding

12 quick questions