0

I am running into this particular issue and was wondering if anyone has come across this particular issue. I have a method: methodA() - this will create a ThreadLocal called "temp" if it doesn't exist, if the ThreadLocal exists, it'll return that ThreadLocal variable (IE: "temp" in this scenario)

Basically the scenario I am running into is this: I call methodA() - (I create the ThreadLocal variable "old_temp") Then I call the method:

CompletableFuture.supplyAsync( () ->{ThreadContext.put("RequestId", requestId); methodB();}, iotaInvokerService).handleAsync(methodC()); Where methodB() is from another team's library and methodB() invokes methodA().

When methodB() invokes methodA(), I want methodA() to return the ThreadLocal variable "old_temp" that was initially created when methodA() was first called. However, when methodB() invokes methodA(), instead of returning the "old_temp" ThreadLocal variable, it creates a completely new ThreadLocal variable to use, which I do not want. When methodB() invokes methodA(), I want it to return "old_temp". Could anyone be able to help me with this scenario?

IE, my belief is that when CompletableFuture.supplyAsync is called with an executorService, it creates a new Thread to which the ThreadLocal variables context are not passed on, which seems to be the problem.

I saw Propagating ThreadLocal to a new Thread fetched from a ExecutorService but I still wasn't sure/still confused on how to apply it to my scenario. I think the thing is that I know what ThreadLocal variable is it that I want, but I am not too sure.

  • 4
    Why do you believe `ThreadLocal` is appropriate here, if you're constantly jumping threads? – Louis Wasserman Oct 31 '22 at 18:33
  • Just because you see a question+answer on StackOverflow, that doesn't mean it is always a good idea to apply it. – DuncG Oct 31 '22 at 18:40
  • The thing is that the external library is using ThreadLocal variables, so that is out of my control. I just want to be able to propagate the information from the parent threadLocal variable to the child one. – spicymaggisauce101 Oct 31 '22 at 19:44

1 Answers1

1

ThreadLocal provides thread-local variables in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. If a computation is started by a thread and continued by another one, then using ThreadLocal seams inappropriate.

If you rely on a library like project reactor, then you can use a Context that is automatically is propagated...

Another option is to use global values (or a singleton that allow access to ...)

mcoolive
  • 3,805
  • 1
  • 27
  • 32