Search code examples
javamultithreadingthread-local

Can a child thread modify its parent's Threadlocal variable?


I have 2 threads each with a Threadlocal list named threadLocal that will both spawn child threads. I want the child threads to be able to modify the parent's threadLocal.

I have tried passing in the parent itself to the child so that it can call parent.threadLocal.get().add(x) but this causes a null pointer exception. When the parent calls threadLocal.get().add(x) it is able to add x to the list just fine.

I know the issue is with the .add(x) because having the child just call .get() does not cause an exception. I also tried passing the threadLocal itself to the child and that gives the same error.

Is there a way to do this?


Solution

  • You can retrieve the list in the parent and pass that to the child, or use InheritableThreadLocal.

    Using InheritableThreadLocal means the value is copied to any child threads.

    Note that in either case, you can't change the value of the parent's ThreadLocal variable, but you can mutate the object the variable refers to. In your case calling .add(...) on the list will work fine, as long as you handle concurrency correctly, e.g. by using CopyOnWriteArrayList