1

I am trying to understand the concept of ThreadLocal concept in Java and I am bit confused.

For example, to define the task of thread we do like this:

public void run() {

  int sum = 0;
  // Code which a thread executes
}

So, if we created say 6 threads, won't each thread have its own "sum" variable as local?

If this is not the concept of ThreadLocal, am i missing something in understand this concept.

Can anyone help me understand this?

CuriousMind
  • 8,301
  • 22
  • 65
  • 134

2 Answers2

3

Local variables within a method are always local to the thread, as they live on the stack. However, instance variables of the class implementing the thread live on the heap and are shared by all threads.

If each thread needs its own copy you need to use ThreadLocal, which under the covers is just a Map<key-class,value-class> where the key is the thread identifier and the value is the thread-local value itself.

Consider a single instance of a class that can be used by multiple threads. Note, I'm NOT referring to the Runnable itself, but to an instance whose methods can be invoked from several different threads. There is a single instance and the class is designed to be used by multiple threads in parallel. So it needs to keep each calling thread's state separate from other threads' state. This is the use case for ThreadLocal.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
  • 1
    Thanks for your answer, I was under the impression that since a "local variable" is local to thread, then what is the deal in this concept. If I understood this correctly, if we have an instance variable at a class level (which has the run()), then for each thread to have its "own" variable , we use the concept of "ThreadLocal"? BTW , has this concept to do anything with "Thread specific Data" which we hear as part of POSIX multi-threading programming in C? – CuriousMind Feb 17 '18 at 19:27
  • See my update, and also read the tagged duplicate question. – Jim Garrison Feb 17 '18 at 19:33
1

sum is not a ThreadLocal variable.

ThreadLocal is an instrument which allows storing values on per-thread basis. Please see the following question for more details:

When and how should I use a ThreadLocal variable?

Consider the following code:

ThreadLocal<Integer> sum = new ThreadLocal();
sum.set(15);

Then, when you call sum.get(), you'll get 15 in the thread where you called sum.set(...) and null in other threads.

ThreadLocal achieves it by maintaining a static map of thread/value.

lexicore
  • 42,748
  • 17
  • 132
  • 221