3

In Java, I have a Thread A. If A spawns a child thread, b, does b have access to any/all ThreadLocal variables that were set by A?

Charles
  • 50,943
  • 13
  • 104
  • 142
Travis Webb
  • 14,688
  • 7
  • 55
  • 109

2 Answers2

7

If you mean InheritableThreadLocal (extending ThreadLocal), then yes, each child thread will have the initial default value to be the same as the parent thread value. But any changes by the child thread will be local to the child.

InheritableThreadLocal doc

Roger Lindsjö
  • 11,330
  • 1
  • 42
  • 53
  • Any changes by the child thread. Will reflect in parent thread. childvalue method had to be override to have different behaviour – Mani Jul 01 '15 at 22:43
  • 2
    The reference to the object will be local to the child. If the child stores another object in the ThreadLocal, then this will not be reflected in the parent. However, if the child modifies the object which the ThreadLocal references, then that will be reflected in the parent. Basically, the child gets a copy of map of thread locals, but the map references the same values as the parent. – Roger Lindsjö Jul 02 '15 at 05:43
  • 1
    Yes. Bottom line, if we set BigInterger value as 1 in parent Threadlocal , while we use inheritableThreadLocal , we will get as 1 in child thread initially . but if we change value to 5 in any one of the child thread, then the Parent Thread and all child's thread of this parent will get 5 . So it has to be use carefully. we can change this behaviour by cloning the instance before return value in childValue method – Mani Jul 05 '15 at 14:19
  • Warning: InheritableThreadLocal does NOT work with thread pools. See: https://stackoverflow.com/questions/9012371/using-inheritablethreadlocal-with-threadpoolexecutor-or-a-threadpoolexecut – Pino Jun 22 '17 at 12:11
4

No, each thread has their own stack. When you create a Thread from another thread they are given a new Thread Stack that is completely different from the creating thread.

John Vint
  • 39,695
  • 7
  • 78
  • 108