Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of ThreadLocal? [duplicate]

The purpose of ThreadLocal as given here states that the variable is local to any Thread accessing an object containing the ThreadLocal variable. What difference does it make, in having a ThreadLocal variable as a member of a class and then making it local to a Thread, rather than having a local variable to the Thread itself?

like image 740
Ajay Avatar asked Sep 29 '09 06:09

Ajay


People also ask

What is the purpose of ThreadLocal?

The ThreadLocal class is used to create thread local variables which can only be read and written by the same thread. For example, if two threads are accessing code having reference to same threadLocal variable then each thread will not see any modification to threadLocal variable done by other thread.

What is the purpose of ThreadLocal in Java?

The Java ThreadLocal class enables you to create variables that can only be read and written by the same thread. Thus, even if two threads are executing the same code, and the code has a reference to the same ThreadLocal variable, the two threads cannot see each other's ThreadLocal variables.

What is the purpose of declaring a variable of type ThreadLocal?

It enables you to create variables that can only be read and write by the same thread. If two threads are executing the same code and that code has a reference to a ThreadLocal variable then the two threads can't see the local variable of each other.

When should ThreadLocal be removed?

You should always call remove because ThreadLocal class puts values from the Thread Class defined by ThreadLocal. Values localValues; This will also cause to hold reference of Thread and associated objects. the value will be set to null and the underlying entry will still be present.


1 Answers

A thread is a unit of execution and so multiple thread can execute the same code at the same time. If multiple threads execute on an object/instance at the same time they will share the instance variables. Each thread will have its own local variables but it is difficult to share these across objects without passing parameters.

It is best explained by way of an example. Say you have a Servlet that gets the logged in user and then executes some code.

doGet(HttpServletRequest req, HttpServletResponse resp) {   User user = getLoggedInUser(req);   doSomething()   doSomethingElse()   renderResponse(resp) } 

Now what happens if the doSomething() methods needs access to the user object? You can't make the user object an instance or static variable because each thread will then use the same user object. You could pass the user object around as a parameter but this quickly becomes messy and leaks user objects into every method call:

doGet(HttpServletRequest req, HttpServletResponse resp) {   User user = getLoggedInUser(req);   doSomething(user)   doSomethingElse(user)   renderResponse(resp,user) } 

A more elegant solution is to put the user object into a ThreadLocal

doGet(HttpServletRequest req, HttpServletResponse resp) {   User user = getLoggedInUser(req);   StaticClass.getThreadLocal().set(user)   try {     doSomething()     doSomethingElse()     renderResponse(resp)   }   finally {     StaticClass.getThreadLocal().remove()   } } 

Now any code that requires the user object at any time can get hold of it by extracting it from the thread local, without needing to resort to those pesky extra parameters:

User user = StaticClass.getThreadLocal().get() 

If you use this approach be mindful to remove the objects again in a finally block. Otherwise the user object might hang around in environments that use a Thread Pool (like Tomcat app server).

Edit: The code for static class

class StaticClass {   static private ThreadLocal<User> threadLocal = new ThreadLocal<>();    static ThreadLocal<User> getThreadLocal() {     return threadLocal;   } } 
like image 196
leonm Avatar answered Oct 07 '22 05:10

leonm