将ThreadLocal与ExecutorService一起使用是否有危险? [英] Is it dangerous to use ThreadLocal with ExecutorService?
问题描述
我在下面的博客中介绍了ThreadLocals的概念:
I was going through the concept of ThreadLocals on the below blog :
https://www.baeldung.com/java-threadlocal
它说不要将ThreadLocal与ExecutorService一起使用"
It says that "Do not use ThreadLocal with ExecutorService"
下面说明了使用ThreadLocals的示例.
It illustrates below example for using ThreadLocals.
public class ThreadLocalWithUserContext implements Runnable {
private static ThreadLocal<Context> userContext
= new ThreadLocal<>();
private Integer userId;
private UserRepository userRepository = new UserRepository();
@Override
public void run() {
String userName = userRepository.getUserNameForUserId(userId);
userContext.set(new Context(userName));
System.out.println("thread context for given userId: "
+ userId + " is: " + userContext.get());
}
// standard constructor
}
文章末尾提到:
如果我们要使用ExecutorService并向其提交Runnable,则使用ThreadLocal会产生不确定的结果-因为我们不能保证每次给定userId的每个Runnable操作都将由同一线程处理它被执行.
If we want to use an ExecutorService and submit a Runnable to it, using ThreadLocal will yield non-deterministic results – because we do not have a guarantee that every Runnable action for a given userId will be handled by the same thread every time it is executed.
因此,我们的ThreadLocal将在不同的userId之间共享.这就是为什么我们不应该将TheadLocal与ExecutorService一起使用.仅当我们完全控制哪个线程将选择要执行的可运行操作时,才应使用它.
Because of that, our ThreadLocal will be shared among different userIds. That’s why we should not use a TheadLocal together with ExecutorService. It should only be used when we have full control over which thread will pick which runnable action to execute.
这个解释对我来说是个保镖.我试图为此专门在网上进行一些研究,但没有得到太多帮助,请一些专家详细解释上述解释吗?是作者观点还是真正的威胁?
This explanation was a bouncer to me. I tried to do some research online for this point specifically but I could not get much help, can some expert please elaborate on the above explanation? Is it authors view or a real Threat?
推荐答案
要注意的要点是您的Runnable
的多个运行可能在不同的线程上执行.可执行程序服务可以由单个线程支持,但也可以由线程池支持.在Runnable
的后续执行中,其他线程将访问其他ThreadLocal
.
The point of that caution is that multiple runs of your Runnable
may execute on different threads. An executor service can be backed by a single thread but it may just as well be backed by a pool of threads. On subsequent executions of your Runnable
, a different thread will be accessing a different ThreadLocal
.
因此,您当然可以使用Runnable内的rel ="nofollow noreferrer"> ThreadLocal
.但这不太可能有用,因为通常ThreadLocal
的目的是保留一个值一段时间.相反,Runnable
通常应该是短命的.
So you certainly can use ThreadLocal
within a single run of the Runnable
. But it is not likely to be useful, as generally the purpose of a ThreadLocal
is to hold a value for a while. In contrast, a Runnable
should generally be short-lived.
所以,不,通常,将ThreadLocal
与线程池一起使用是没有意义的.
So, no, generally it does not make sense to use a ThreadLocal
with a thread pool.
这篇关于将ThreadLocal与ExecutorService一起使用是否有危险?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!