ThreadLocal Remove Resets Stale Pool State
Reuse a single pooled thread with and without ThreadLocal.remove: stale state leaks to the next borrower until remove re-runs withInitial.
Code
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadLocalPoolReuse {
// withInitial:线程首次 get() 才创建自己的 state
static final ThreadLocal<StringBuilder> SCRATCH =
ThreadLocal.withInitial(() -> new StringBuilder("init"));
public static void main(String[] args) {
ExecutorService pool = Executors.newSingleThreadExecutor();
// 借用者 A:改写后忘记 remove
pool.submit(() -> {
SCRATCH.get().append(" -> borrowerA");
System.out.println("A sees: " + SCRATCH.get());
});
// 借用者 B:线程被复用,拿到 A 留下的 stale 残留
pool.submit(() -> System.out.println("B sees: " + SCRATCH.get()));
// 借用者 C:用完 remove(),之后 get() 重新走 withInitial (reset)
pool.submit(() -> {
SCRATCH.get().append(" -> borrowerC");
System.out.println("C before remove: " + SCRATCH.get());
SCRATCH.remove();
System.out.println("C after remove: " + SCRATCH.get());
});
pool.shutdown();
}
}ThreadLocal Remove Resets Stale Pool State: the mechanics
ThreadLocal Remove Resets Stale Pool State reduces to the class ThreadLocalPoolReuse and the function main.
What to watch for
- Nothing arrives from a registry; the language ships every API used.
Using it
The definition that matters: public static void main(String[] args)
Each relevant output line starts with A sees:, B sees:, C before remove:.
Key statements
ExecutorService pool = Executors.newSingleThreadExecutor();
ThreadLocal.withInitial(() -> new StringBuilder("init"));
Interactive Tools for This Topic
FAQ
- What does ThreadLocal Remove Resets Stale Pool State print when run?
- Running the file directly is enough — expect labeled output lines such as `A sees:`, `B sees:`, `C before remove:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.