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
?
Asked
Active
Viewed 5,025 times
3

Charles
- 50,943
- 13
- 104
- 142

Travis Webb
- 14,688
- 7
- 55
- 109
-
4**ThreadScope**? There is no such thing in Java. Do you mean **ThreadLocals**? If this is what you mean, no, they don't have access to other thread's thread local variables. – Maurício Linhares Jan 25 '12 at 17:45
-
yes `ThreadLocal` is the object, sorry about that. `ThreadLocal` creates thread-scopred variables, whence my confusion. – Travis Webb Jan 25 '12 at 18:14
-
What does the term "child" mean in this context? What is a "child thread"? – David Schwartz Mar 09 '16 at 03:05
2 Answers
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.

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
-
2The 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
-
1Yes. 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