ThreadLocal and the classic thread-pool memory leak
ThreadLocal<T> gives every thread its own independent copy of a variable -- no synchronization needed,
since threads never actually share the storage. The well-known production trap: in a thread pool, threads
are reused across many tasks/requests. A ThreadLocal value set during one task and never cleared stays
attached to that pooled thread indefinitely, silently leaking (and potentially leaking into the next,
unrelated task run on the same thread) unless you explicitly remove() it when done.
class Counters {
static ThreadLocal<Integer> counter = ThreadLocal.withInitial(() -> 0);
}
Runnable task = () -> {
int val = Counters.counter.get();
Counters.counter.set(val + 1);
System.out.println(" " + Thread.currentThread().getName() + " sees: " + Counters.counter.get());
};
Thread t1 = new Thread(task, "thread-A");
Thread t2 = new Thread(task, "thread-B");
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println("main thread's own value (completely independent, never touched by t1/t2): " + Counters.counter.get());
In a real thread pool, t1/t2 above would be reused for future tasks -- and without counter.remove() at the end of each task, this value would silently persist across unrelated work items run on the same pooled thread. The idiomatic fix is a try/finally that calls remove() unconditionally.