1

I would like to associate a variable / value with a thread so that I don't have to explicitly pass it down the call stack. It's basically a global variable that is scoped to the current thread.

I have a method that needs to define a variable that will be accessible in the callstack x more methods deep. I don't want to have to pass it all X method layers deep.

Everywhere I search folks give examples using the ThreadLocal class. Maybe I'm missing something, but using ThreadLocal, how do I get a reference to the ThreadLocal variable when I'm X levels deep in a method calls?

All help is appreciated.

  • 1
    Seems like all you need is to read further on ThreadLocals. It will work. The first answer [here](https://stackoverflow.com/questions/817856/when-and-how-should-i-use-a-threadlocal-variable) gives an example. It also helps to actually try the examples in addition to just reading them. – ernest_k Jan 27 '20 at 16:05

1 Answers1

2

Just create a publicly accessible instance of ThreadLocal and call the get() method. e.g. you could have a

public class ThreadHelper {
    public static final ThreadLocal<T> THREAD_MAP = new ThreadLocal<>();
}

Then just use that...

...
ThreadHelper.THREAD_MAP.get();
...

Or you could use the Singleton pattern. etc.

tomgeraghty3
  • 1,234
  • 6
  • 10