An important point in the ThreadLocal variable is global access. It can be accessed from anywhere in the stream. In any case, which causes this thread context.
If you want to save one instance of a variable for all instances of the class, you will use member variables of the static class for this. If you want to maintain a variable instance for each thread, you will use local thread variables. ThreadLocal variables differ from ordinary variables in that each thread has its own individually initialized instance of the variable, which it accesses through the get () or set () methods.
Suppose you are developing a multi-threaded code tracer whose purpose is to uniquely identify each flow path through your code. The problem is that you need to coordinate multiple methods in multiple classes across multiple threads. Without ThreadLocal, this would be a difficult problem. When the thread started executing, it will need to create a unique token to identify it in the tracer, and then pass this unique token to each method in the trace.
With ThreadLocal, everything is simpler. A thread initializes a local thread variable at the start of execution, and then accesses it from each method in each class with the confidence that the variable will only contain trace information for the current executable thread. When this is done, the thread can send its trace, depending on the thread, to the control object responsible for maintaining all the traces.
Using ThreadLocal makes sense when you need to store instances of variables on each thread.
source share