8

I have passed one object in ThreadLocal. Now my current thread going to create new Child thread. I want object from ThreadLocal should continue with child thread also.

Is there any way to do so....?

Thank you in advance....

user574557
  • 243
  • 5
  • 14

2 Answers2

25

What you need is an InheritableThreadLocal. An InheritableThreadLocal is passed (Java "call by value" semantics) from the parent thread to a child thread when the latter is created.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 2
    [This answer](https://stackoverflow.com/questions/7259906/propagating-threadlocal-to-a-new-thread-fetched-from-a-executorservice/7260192#7260192) suggests the `InheritableThreadLocal` will not work with thread pools, because threads are reused. What's your take on this? – Dormouse Nov 04 '18 at 12:15
  • 2
    It is correct. If you use a thread pool, you can't pass values between parent and child threads using thread locals. But that is not what >>this<< question is asking about. Read the second sentence carefully. It implicitly precludes the use of thread pools. Compare it with the other question. They are different in that important respect. – Stephen C Nov 04 '18 at 12:25
  • True, it's a very important nuance that deserves to be mentioned though. Especially with Java 8's `Stream.parallel()` nowadays. – Dormouse Nov 04 '18 at 12:35
  • Be careful with `InheritableThreadLocal`: https://stackoverflow.com/questions/41293485/inheritablethreadlocal-value-not-inherited-by-executorservice-threads – Dedkov Vadim Mar 15 '19 at 16:51
  • [URGENT] Then how to enforce sharing the same ThreadLocal as parent, so that any updates in done by child Thread is also visible to parent thread? Can we override childValue method to return same contained object as of parent to make it work? – bit_cracker007 Jul 27 '21 at 16:40
  • I don't think that you can. Think of an alternative approach; e.g. sharing a mutable thread-safe object via `InheritableThreadLocal` ... or share it some other way. – Stephen C Jul 27 '21 at 23:28
1

You may retrieve the object itself from your ThreadLocal via the get() method and pass this reference to you child thread.

If instead you want to share it with your child threads, see other answers.

Howard
  • 38,639
  • 9
  • 64
  • 83
  • Technically, inheritable thread locals are not shared. Each child thread gets its own thread local variable ... which is initialized from the parent thread's local. – Stephen C Jul 01 '13 at 09:30
  • [URGENT] Then how to enforce sharing the same ThreadLocal as parent, so that any updates in done by child Thread is also visible to parent thread? Can we override childValue method to return same contained object as of parent to make it work? – bit_cracker007 Jul 27 '21 at 16:40