Wednesday, October 24, 2012

ThreadLocal

ThreadLocal is a class that lets you wrap an object inside it so that each thread accessing ThreadLocal will get its own copy of the object. Consider the following example.

Suppose I have a multithreaded application. The main purpose of each thread in the application is to modify an object through long running processes by calling so many methods (OK this is quite unrealistic example :p). Each thread has its own object to modify. We can declare the object variable in the Thread class or Runnable implementation class or pass it around the methods but obviously it is not a good practice and not always can be done. To overcome this, we can use ThreadLocal.

Images below show us how to implement this: First we have the object to be manipulated, in this case it is a POJO.



Next, we will create a main class which has three threads. Each thread is intended to manipulate a User.



Now we will see the Runnable class to manipulate the object. In the run() method we can see that we modify the user's address in another method and try to see if the changes are persisted correctly. In real life, this is the long-running process that calls many methods to modify the User object.



It's the time to see the ThreadLocal variable in UserFactory class. In the UserFactory class we create a ThreadLocal variable and implement it anonymously. The initialValue() is called only once so it is the best place to initiate everything. All other method's names are quite self-explanatory.



The results are shown below. We can see that each thread has exactly one copy of the User object and the User in each thread is modified correctly. ThreadLocal is very convenient to store an object to be accessible throughout the thread.

0 comments:

 

©2009 Stay the Same | by TNB