ThreadLocal in Java

SHARE & COMMENT :

ThreadLocal is one of the rarely used class in Java. I found it is one of the powerful class in Java on multi-threaded programming. In multi threaded program generally we use session object to track the current users information.

also read:

These information is passed to various method to retrieve desired value. For example in Struts execute method passes HttpServletRequest and HttpServletResponse, what if we want the instance of ServletContext? we have to change the method signatore to pass ServletContext. One can use ThreadLocal to keep certain objects/values available throught the thread execution.

ThreadLocal object is not required on day to day programming unlike ArrayList or HashMap. But it is good choice to solve a few problem at framework level.

In one of my recent project I have used ThreadLocal to expose user specific information like UserPreferences, UserId, Permissions, etc. The main reason is I want hide the code which identifies these values so that in future it is easy to change the behavior and fine tune the code across the application.

A neat example of a “good” use of ThreadLocal is in JSF and FacesContext.getInstance(). Compare this to many other frameworks which forces framework users to pass HttpRequest around, polluting method signatures all over the place, because somewhere deep inside there might be some bloody utility method that needs.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better