Java – can ThreadLocal be safely used with Tomcat NiO connector
We thought of this when testing the Tomcat NiO connector during the load test I use ThreadLocal. In addition, I use spring. I know it also uses it in several places
Since NiO connector does not have a thread per connection, I am worried that if the ThreadLocal object is shared with another thread before cleaning, it may be difficult to find the error However, I don't think this is a problem because it's not a file warning I can find, and I haven't found any other posts warning this I assume that the NiO connector has no effect on the threads serving the actual request
Before I adopt this hypothesis, I hope to find some concrete evidence
Solution
Only those who are familiar with Tomcat code can give you a specific answer, but I will try a wooden one:)
First, you need to know if you're just using NiO connectors, or if you're talking about async servlets The answer will be slightly different in each case
The main thing to note is that Java does not have any type of continuation, collaborative routine or thread rearrangement This means that once you start a code that runs on a thread, only that code will run on the thread until it is completed
So if you have: MyObject doSomething(); Then when dosomething runs, it has exclusive access to the thread The thread will not switch to other code - no matter what type of IO model you are using
What may happen is that different threads will be scheduled to run on different CPUs, but each thread will run a piece of code to complete
So if dosomething is:
public static final ThreadLocal<MyClass> VALUE = new ThreadLocal<MyClass>(); public void doSomething() { VALUE.set(this); try { doSomethingElse(); } finally { VALUE.set(null); } }
Then there's nothing to worry about - dosomethingelse will run a thread and ThreadLocal will be set to the correct value for the entire execution
Therefore, a simple NiO connector should make no difference - the container will call the service method on the servlet, the servlet will execute in a single thread, and then finally complete all operations Only the container can handle IO in a more efficient way when handling connections
If you are using an asynchronous servlet, it will be different – in this case, your servlet may be called multiple times for a single request (because of the way the asynchronous model works), and these calls may be on different threads, so you can store something thread local between servlet calls But it's still fine for calling your service method at once
HTH.