← 中文资源

简体中文版本

ThreadLocal remove 重置线程池残留

线程池复用线程:不 remove 的借用者会把改写过的 state 留给下一个借用者;remove 之后 get() 重新走 withInitial 拿到干净初值。

阅读英文原文

实现说明

逻辑集中在类 ThreadLocalPoolReuse和函数 main里。

使用要点

  • 跑完文件,输出里会留下标记——A sees:、B sees:、C before remove:。

常见问题

运行「ThreadLocal remove 重置线程池残留」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 A sees:、B sees:、C before remove: 标签标明各步骤。

核心语句

ExecutorService pool = Executors.newSingleThreadExecutor();
ThreadLocal.withInitial(() -> new StringBuilder("init"));

代码示例

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();
    }
}