Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is ThreadLocal preferred over Local Variables?

ThreadLocal in Java says that:

The ThreadLocal class in Java 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 a ThreadLocal variable, then the two threads cannot see each other's ThreadLocal variables.

My question is: When we need to get a variable specific to a thread, can't we just declare that variable as a local variable inside a method? Because every thread has its own stack and thus it gets its own copy of variables. Am I missing something here?

like image 309
user3329002 Avatar asked Jul 19 '16 01:07

user3329002


People also ask

When should I use ThreadLocal?

ThreadLocal is useful, when you want to have some state that should not be shared amongst different threads, but it should be accessible from each thread during its whole lifetime. As an example, imagine a web application, where each request is served by a different thread.

What is valid about ThreadLocal?

Java ThreadLocal class provides thread-local variables. 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.

What is ThreadLocal class how can it be used?

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.


2 Answers

ThreadLocal is is not an alternative to local variables. You use ThreadLocal for data that have to be static, but which must not be shared between threads.

static final ThreadLocal<MyFoo> myFoo =
    ThreadLocal.withInitial(() -> new MyFoo());

If you have a ThreadLocal variable that is not static, then you're either doing something that's overly complicated, or you're doing something that's just plain wrong.

On the other hand, if you have any variable that is static (whether it is ThreadLocal or not), then you should be aware that that's a design choice that will limit your ability to test and grow the program.

like image 144
Solomon Slow Avatar answered Sep 22 '22 01:09

Solomon Slow


ThreadLocal was meant for different purpose as per oracle documentation.

Have a look at intent of this class:

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

Below code block generates unique identifiers local to each thread. A thread's id is assigned the first time it invokes ThreadId.get() and remains unchanged on subsequent calls.

 import java.util.concurrent.atomic.AtomicInteger;

 public class ThreadId {
     // Atomic integer containing the next thread ID to be assigned
     private static final AtomicInteger nextId = new AtomicInteger(0);

     // Thread local variable containing each thread's ID
     private static final ThreadLocal<Integer> threadId =
         new ThreadLocal<Integer>() {
             @Override protected Integer initialValue() {
                 return nextId.getAndIncrement();
         }
     };

     // Returns the current thread's unique ID, assigning it if necessary
     public static int get() {
         return threadId.get();
     }
 }

Coming back to your query:

When we need to get a variable specific to a thread, can't we just declare that variable as a local variable inside a method? Because every thread has its own stack and thus it gets its own copy of variables. Am I missing something here?

Yes. You are missing something here.

The scope of variable , which was declared inside a method ends with the method life cycle.

In case of ThreadLocal varaibles, each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible. You can re-enter the thread multiple times in it's life cycle and still you can retain the variable.

like image 44
Ravindra babu Avatar answered Sep 20 '22 01:09

Ravindra babu