Java.lang.ThreadLocal Class in Java
This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. Basically, it is another way to achieve thread safety apart from writing immutable classes. Since the Object is no more shared there is no requirement for Synchronization which can improve the scalability and performance of the application. ThreadLocal provides thread restriction which is an extension of a local variable. ThreadLocal is visible only in a single thread. No two threads can see each other’s thread-local variable. These variables are generally private static fields in classes and maintain their state inside the thread.
Note: ThreadLocal class extends Object class
Constructor: ThreadLocal(): This creates a thread-local variable.
Methods of ThreadLocal Class
|get()||Returns the value in the current thread’s copy of this thread-local variable. If the variable has no value for the current thread, it is first initialized to the value returned by an invocation of the initialValue() method|
|initialValue()||Returns the current thread initial value for the local thread variable.|
|remove()||Removes the current thread’s value for this thread-local variable. If this thread-local variable is subsequently read by the current thread, its value will be reinitialized by invoking its initialValue() method, unless its value is set by the current thread in the interim. This may result in multiple invocations of the initialValue method in the current thread|
|set()||Sets the current thread’s copy of this thread-local variable to the specified value. Most subclasses will have no need to override this method, relying solely on the initialValue() method to set the values of thread locals.|
value = 100 value = 90 value = 88.45 value = GeeksforGeeks
value = 100 value = 90 value = 88.45 value = GeeksforGeeks value = null value = null
This article is contributed by Abhishek Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.