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.
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 signature to pass ServletContext. One can use ThreadLocal to keep certain objects/values available throughout 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 et al around, polluting method signatures all over the place, because somewhere deep inside there might be some bloody utility method that needs.
Notes:
- Code which depends directly on a ThreadLocal can be difficult to test (on par with code which depends directly on a static variable).
- Remember to explicitly clear the value in ThreadLocal to prevent memory leaks. Don’t forget this, especially if you are using thread pools.
- ThreadLocal concept is not specific to Java. The same feature is available in many other languages as well. See Wikipedia definition here.
Delicious
Digg
reddit
Facebook
StumbleUpon

Leave a comment