简体   繁体   English

如何从Java中的另一个线程访问ThreadLocal中的信息

[英]How to access information in ThreadLocal from another thread in Java

I am working with a Java web application backend. 我正在使用Java Web应用程序后端。 We have a Servlet that in the init() method has 我们有一个Servlet,它在init()方法中具有

public static final ThreadLocal<HttpServletRequest> REQUEST_HOLDER = new ThreadLocal<HttpServletRequest>();

In the service() method 在service()方法中

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException

the Servlet then sets the value of REQUEST_HOLDER with the request. 然后,Servlet通过请求设置REQUEST_HOLDER的值。

REQUEST_HOLDER.set(request);

Later in the servlet, I want to do some heavy processing on another thread, but still reference the request from the ThreadLocal REQUEST_HOLDER, which is technically on a different thread. 稍后在servlet中,我想在另一个线程上进行一些繁重的处理,但仍引用ThreadLocal REQUEST_HOLDER的请求,该请求在技术上是在另一个线程上。 Is this possible? 这可能吗? how? 怎么样? (new to multithreading) (多线程新手)

Although this general concept has largely been addressed in ThreadLocal value access across different threads , I want to know if there is anything unique regarding servlets / http requests that might provide a different solution. 尽管在不同线程间的ThreadLocal值访问中已大致解决了这一一般概念,但我想知道关于servlet / http请求是否有任何独特之处可能会提供不同的解决方案。 If not, not. 如果没有,那就没有。

Also is it possible to take the REQUEST_HOLDER ThreadLocal and override the get() method so that if it is null (as in when called from a different thread) it returns a different value? 还可以采用REQUEST_HOLDER ThreadLocal并重写get()方法,以便如果该方法为null(例如从其他线程调用时),则返回不同的值吗? - thinking of storing the request somewhere else and have the get() return that value. -考虑将请求存储在其他位置,并让get()返回该值。

另一种解决方案而不是弄乱ThreadLocal机制,是从主线程中的请求对象中提取所有必要的数据,将其放入单独的数据对象中,然后将此对象提供给新线程。

A coworker suggested to me that when I start the new Thread, I should pass in the request. 一位同事向我建议,当我启动新线程时,我应该传递请求。 Then in the new thread I can set the ThreadLocal REQUEST_HOLDER with the request from the new thread. 然后在新线程中,我可以使用新线程的请求来设置ThreadLocal REQUEST_HOLDER。 Thanks all for your answers 谢谢大家的回答

As per the Java documentation , ThreadLocal variables are initialized so that they are only visible to individual threads. 根据Java 文档 ,将初始化ThreadLocal变量,以便它们仅对单个线程可见。

Of course any value can be shared, so one could just make the Object value returned by the ThreadLocal get() method accessible to other threads, but that defeats the purpose of having such a variable in the first place. 当然,任何值都可以共享,因此可以使ThreadLocal get()方法返回的Object值可被其他线程访问,但这首先破坏了使用此类变量的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM