Thread Local Variables


Have you ever thought of havinh thread level local variable? Interestingly there is a way to use that. since Java 1.2 and today only I came to know that 😦
ThreadLocal is the class you can use for that.
One main advantage I found (in fact my requirement) is that thread itself can carry information with it. Which means if you have a method
processFile(String fileName)
Using ThreadLocal you can pass additional information to this method apart from the String fileName parameter, which will be carried safely inside the thread executing it. Its useful especially when you have a big chain of method calls and you need to pass an additional information to the last method from the first one. Using ThreadLocal you just need to update the first method to set the additional information and last method to read from it.
Another obvious advantage is its thread safe!!! Its local to a thread, so no other thread can access it. For the same reason Spring stores the session variable as ThreadLocal.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s