# When and how to use InheritableThreadLocal

Today I was reading Spark’s source code, and found InheritableThreadLocal in it. Little information could be found online about this class, so I decided to write a blog to illustrate how to use it, based on the experiments I did.

Before diving into InheritableThreadLocal, we need to understand ThreadLocal. ThreadLocal is used to create separate variables for each thread, as follows.

Output

The above code is written in Scala.

As you can see, thread1 and thread2 have different values for number, because we use ThreadLocal here, so the result is different.

Now we decided to start a child thread within thread1/thread2, obtain the value of number and print it, can we achieve it?

Output

No, we cannot, because threadLocal cannot be passed into child threads. But what if we want it to do so? Just use InheritableThreadLocal!

Output

Notice that we cannot set the value of InheritableThreadLocal in the child thread.

Output

As you can see, setting the value of InheritableThreadLocal doesn’t have any effect.

Share