java thread 清除_java – 线程返回线程池后是否清除ThreadLocal对象?

除非您这样做,否则ThreadLocal和ThreadPool不会相互交互.

您可以做的是一个ThreadLocal,它存储您要保留的所有状态,并在任务完成时重置该状态.您可以覆盖ThreadPoolExecutor.afterExecute(或beforeExecute)以清除ThreadLocal(s)

来自ThreadPoolExecutor

/**

* Method invoked upon completion of execution of the given Runnable.

* This method is invoked by the thread that executed the task. If

* non-null, the Throwable is the uncaught {@code RuntimeException}

* or {@code Error} that caused execution to terminate abruptly.

*

*

This implementation does nothing, but may be customized in

* subclasses. Note: To properly nest multiple overridings, subclasses

* should generally invoke {@code super.afterExecute} at the

* beginning of this method.

*

... some deleted ...

*

* @param r the runnable that has completed

* @param t the exception that caused termination, or null if

* execution completed normally

*/

protected void afterExecute(Runnable r, Throwable t) { }

您可以立即清除所有ThreadLocals,而不是跟踪所有ThreadLocals.

protected void afterExecute(Runnable r, Throwable t) {

// you need to set this field via reflection.

Thread.currentThread().threadLocals = null;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值