In Java, when the ThreadLocal object is modified, will the change be retained in the next request?
In a typical web application, when a request enters, the filter looks for the context object in the HTTP session If it does not exist, the context object is created and stored in the HTTP session In addition, this context object is also stored in the ThreadLocal object The servlet under the path retrieves this context object from ThreadLocal and modifies it When the response is returned, the filter now makes the context object in ThreadLocal null Therefore, when the user makes another request, can he see the modified context object?
Thank you, Quaid
Solution
Yes, the user will see the context object because the reference to it is stored in httpsession Although the reference in ThreadLocal is empty, it will still be found in the session during the second request
Edit: in the openjdk sourcecode of ThreadLocal (from line 410), you can see the difference between the set and remove methods of ThreadLocal Calling set (null) will leave the threadlocalmap entry null, while remove () will completely delete it It has no impact on your problem, and your context object will still be referenced in the session
When I first read your question title, I explained it differently because I didn't mention httpsession or clear ThreadLocal Perhaps this confused some respondents It sounds like you want to know if the ThreadLocal variable set in the first request can still be accessed in the first request (and not cleared) I think the answer is, it depends on how your web server handles threads If a thread pool of 10 threads is randomly reused, you should have a 10% chance of finding the same ThreadLocal variable in the second request