Monday 8 February 2016

Secret of java.lang.Threadlocal - Part II

What is ThreadLocal ?

The ThreadLocal class is provided by Java core API as part of java.lang package. This class is used to maintain the individual local copy for each thread. Even if two threads are executing the same code, and the code has a reference to a ThreadLocal variable, then the two threads cannot see each other's ThreadLocal variables.

Let's see an example to understand better.


Output:
First generated : 101
Second generated : 102
Second generated : 104
Second generated : 105
Second generated : 106
Second generated : 107
First generated : 103
First generated : 108
First generated : 109
First generated : 110

Here we are expecting two generator threads should generate IDs starting from the supplied initial value (100). But observer here in o/p,  since the threads are sharing the common variable currentId, it fails to generate the required IDs as there is only one copy of the variable for all threads. To resolve this issue we have to maintain an individual copy for each thread so that there will not be any conflict among the threads.

Example with our own custom ThreadLocal class (MyThreadLocal.java)


Output:
First generated : 101
First generated : 102
First generated : 103
First generated : 104
Second generated : 101
First generated : 105
Second generated : 102
Second generated : 103
Second generated : 104
Second generated : 105

Now here each thread is generating the IDs starting from 100 individually with the same common variable currentId but declared as MyThreadLocal. 

java.lang.ThreadLocal also works in similar fasion. So instead of creating your own custom ThreadLocal class you can use that class as that having more flexibility and other benefits. This MyThreadLocal class I have written to demonstrate how internally java.lang.Threadlocal class works.



Thanking you for visiting this blog. Please feel free to share your comment/suggestion.


No comments:

Post a Comment