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?
ThreadLocal
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.