TheThreadLocal
class in Java enables you to create variables that can only be read and written by the same thread. Thus, even if two threads are executing the same code, and the code has a reference to aThreadLocal
variable, then the two threads cannot see each other'sThreadLocal
variables.
Creating a ThreadLocal
Here is a code example that shows how to create aThreadLocal
variable:
private ThreadLocal myThreadLocal = new ThreadLocal();
As you can see, you instantiate a newThreadLocal
object. This only needs to be done once per thread. Even if different threads execute the same code which accesses aThreadLococal
, each thread will see only its ownThreadLocal
instance. Even if two different threads set different values on the sameThreadLocal
object, they cannot see each other's values.
Accessing a ThreadLocal
Once aThreadLocal
has been created you can set the value to be stored in it like this:
myThreadLocal.set("A thread local value");
You read the value stored in aThreadLocal
like this:
String threadLocalValue = (String) myThreadLocal.get();
Theget()
method returns anObject
and theset()
method takes anObject
as parameter.
Generic ThreadLocal
You can create a genericThreadLocal
so that you do not have to typecast the value returned byget()
. Here is a genericThreadLocal
example:
private ThreadLocal
<
String
>
myThreadLocal = new ThreadLocal
<
String
>
();
Now you can only store strings in theThreadLocal
instance. Additionally, you do not need to typecast the value obtained from theThreadLocal
:
myThreadLocal.set("Hello ThreadLocal");
String threadLocalValue = myThreadLocal.get();
Initial ThreadLocal Value
Since values set on aThreadLocal
object only are visible to the thread who set the value, no thread can set an initial value on aThreadLocal
usingset()
which is visible to all threads.
Instead you can specify an initial value for aThreadLocal
object by subclassingThreadLocal
and overriding theinitialValue()
method. Here is how that looks:
private ThreadLocal myThreadLocal = new ThreadLocal
<
String
>
() {
@Override protected String initialValue() {
return "This is the initial value";
}
};
Now all threads will see the same initial value when callingget()
before having calledset()
.
Full ThreadLocal Example
Here is a fully runnable JavaThreadLocal
example:
public class ThreadLocalExample {
public static class MyRunnable implements Runnable {
private ThreadLocal
<
Integer
>
threadLocal =
new ThreadLocal
<
Integer
>
();
@Override
public void run() {
threadLocal.set( (int) (Math.random() * 100D) );
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println(threadLocal.get());
}
}
public static void main(String[] args) {
MyRunnable sharedRunnableInstance = new MyRunnable();
Thread thread1 = new Thread(sharedRunnableInstance);
Thread thread2 = new Thread(sharedRunnableInstance);
thread1.start();
thread2.start();
thread1.join(); //wait for thread 1 to terminate
thread2.join(); //wait for thread 2 to terminate
}
}
This example creates a singleMyRunnable
instance which is passed to two different threads. Both threads execute therun()
method, and thus sets different values on theThreadLocal
instance. If the access to theset()
call had been synchronized, and it hadnotbeen aThreadLocal
object, the second thread would have overridden the value set by the first thread.
However, since itisaThreadLocal
object then the two threads cannot see each other's values. Thus, they set and get different values.
InheritableThreadLocal
TheInheritableThreadLocal
class is a subclass ofThreadLocal
. Instead of each thread having its own value inside aThreadLocal
, theInheritableThreadLocal
grants access to values to a thread and all child threads created by that thread.