Why we need Thread Local variable?
Objective of thread local class is to share information across multiple threads where each thread will have independent copy of the variable.Normally in multi threaded programs each thread tries to modify the shared information.If we want exclusive right to that state variable,we introduce synchronization which is expensive.However if our use case involves frequent read operations , less number of modify operations and no interdependence among state variables across different threads,we can use thread local variables.We use thread local variables when each thread wants to get default initialized copy of the variable and modify it as per their algorithm and use it across.It does not depend what would be the value of state variable in different threads.
How to create Thread Local variable?
All we have to do is to create a subclass of thread local and provide implementation for initial value.Normally we achieve this by creating anonymous inner sub class.Then whenever we want to access/update the value we use corresponding get and set methods.Lets take one use case in which we span multiple threads and create a thread local variable for the simple date format.Here depending upon the thread name we set date format in thread local variable which is then used by another class to print the current date.
Attached is the code snippet for reference.
Where all thread locals are used?
Its widely used in lots of frameworks like Spring ,Hibernate and others for passing particular thread specific information like transaction attributes,connection details,authorization information and others.
Is Thread Local safe to use or does it have some issues?
If thread local variables are not handled properly,it may lead to Class loader memory leak issue.Normally we get errors like this OutOfMemory: PermGen error...............................Reason being if we don't clear the thread local variables after use and if thread local variables references some object.It will still be there and won't be garbage collected even though thread has finished the execution.Gradually with multiple installations/un-installations or multiple threads being spawned this memory issue will cause application to crash .So we should take proper care of removing the referencing to objects in thread local variables after use.
Hope it makes things clearer about Thread Local.Comments are welcome