What is the use of ThreadLocal class in Java? What are the scenarios suitable for using ThreadLocal class?
What is the use of ThreadLocal class in Java?
ThreadLocal class provides thread-local variables. Each thread accesses only its own local variables. It has its own copy of the variable.
By using ThreadLocal, if thread X stores a variable with value x and another thread Y stores same variable with the value y, then X gets x from its ThreadLocal instance and Y gets y from its ThreadLocal instance.
Typically, ThreadLocal instances are private static fields that are associated with the state of a thread.
What are the scenarios suitable for using ThreadLocal class in Java?
We can use instance of ThreadLocal class to transport information within an application.
One use case is to transport security or login information within an instance of ThreadLocal so that every method can access it.
Another use case is to transport transaction information across an application, without using the method-to-method communication.
Comments
Post a Comment