Search code examples
javamultithreadingthread-local

Can child's ThreadLocal be modified with the parent's ThreadLocal value?


I am working with InheritableThreadLocal and I know that when creating the children the ThreadLocal will have the default value the same as the parent thread value. But how can I maintain this when the parent's ThreadLocal value is modified?

Is there a way that when the parent's ThreadLocal is modified, all his children threads receive that modification?

EDIT: I have a boolean set on false in my parent thread. But I have a condition and when that happens I set the boolean to true and I need to do this also for all the children threads that were spawned by my initial thread.


Solution

  • InheritableThreadLocal only helps set the initial value in the child. It does not provide any other synchronization. You have to use normal thread synchronization methods to propagate the value.

    That said, if you want all the children to have the same value of the parent both at start and when the parent changes, then why are you giving them all separate objects that need to be synchronized? Why not give the children a reference to the parent and have them all check the parent's value?