ThreadLocal in Java

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 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 problems at framework level. In one of my recent project I have used ThreadLocal to expose user specific information like User info, UserId, Roles and access, 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.

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 )

Connecting to %s