|Java ThreadLocal is an interesting and important Class in Java where most the developers unaware of it. Lets see what is Java ThreadLocal by its importance and how to use it with simple sample code.|
What is Java ThreadLocal?
Java ThreadLocal gives the scope of an Object which stored in the ThreadLocal. We can set any Object in the Thread Local which inturns to be global access for the Thread from anywhere.
Only thing which we need to keep in mind that to maintain a separate instance copy for each thread, so that Object conflict won't occur between multiple threads.
Values stored in ThreadLocal are local to each threads, i.e., each thread will have it's own ThreadLocal Objects where one thread can not access/modify other thread's Thread Local Objects unless it satisfies preview statement.
Where to use Java ThreadLocal?
Lets a take situation that we need to use some global value for each thread which can be access across and anywhere the Thread is been called (For example in any methods). In those cases we can value or Object in ThreadLocal and same value or Object can be accessed anywhere in particular Thread call.
There are 4 methods in ThreadLocal class and they are
- initialValue() - Returns the current thread's "initial value" for this thread-local variable.
- get() - Returns the value in the current thread's copy of this thread-local variable.
- set() - Sets the current thread's copy of this thread-local variable to the specified value.
- remove() - Removes the current thread's value for this thread-local variable.
Lets see simple example how to use ThreadLocal in Java.