与线程关联的一组ThreadLocal实例被保存在每个线程的私有成员中。你唯一可以枚举这些的机会是在线程上做一些反思;这样,您可以覆盖线程的字段上的访问限制。
一旦可以获得一组ThreadLocal,您可以使用ThreadPoolExecutor的beforeExecute()和afterExecute()钩子在后台线程中复制,或者通过为拦截run()调用的任务创建一个Runnable包装器来设置一个未设置的必要的ThreadLocal实例。实际上,后一种技术可能会更好的工作,因为它会给您一个方便的地方在任务排队时存储ThreadLocal值。
更新:这是第二种方法的更具体的例子。与我的原始描述相反,存储在包装器中的所有内容都是调用线程,在执行任务时被询问。
static Runnable wrap(Runnable task)
{
Thread caller = Thread.currentThread();
return () -> {
Iterable> vars = copy(caller);
try {
task.run();
}
finally {
for (ThreadLocal> var : vars)
var.remove();
}
};
}
/**
* For each {@code ThreadLocal} in the specified thread, copy the thread's
* value to the current thread.
*
* @param caller the calling thread
* @return all of the {@code ThreadLocal} instances that are set on current thread
*/
private static Collection> copy(Thread caller)
{
/* Use a nasty bunch of reflection to do this. */
throw new UnsupportedOperationException();
}
线程局部变量管理
1140

被折叠的 条评论
为什么被折叠?



