java.lang.ThreadLocal provides a way to associate an object instance to the current thread. With the help of ThreadLocal, we can create an object whose scope is associated to a thread instance. In this tutorial we are going to understand this feature with an example:
Creating an Object
public class MyObject {
private String name;
public MyObject(String name) {
this.name = name;
}
public void showName() {
System.out.printf("MyObject name: %s, thread: %s%n", name,
Thread.currentThread().getName());
}
}
Using ThreadLocal
We typically provide an static access to ThreadLocal object. ThreadLocale.set(..) method is used to associate an object's instance to the current thread and ThreadLocal.get() methods is to get that instance back.
public class MyThreadLocal {
private static final ThreadLocal<MyObject> threadLocal = new ThreadLocal<>();
public static MyObject createMyObject(String name) {
MyObject myObject = new MyObject(name);
threadLocal.set(myObject);
return myObject;
}
public static MyObject getMyObject() {
return threadLocal.get();
}
}
The main class
public class ExampleMain {
public static void main(String[] args) {
String[] names = {"one", "two", "three"};
Arrays.stream(names)
.forEach(ExampleMain::createThread);
}
private static void createThread(final String name) {
new Thread(() -> {
MyThreadLocal.createMyObject(name);
for (int i = 0; i < 5; i++) {
MyThreadLocal.getMyObject().showName();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
} OutputMyObject name: one, thread: Thread-1 MyObject name: two, thread: Thread-2 MyObject name: three, thread: Thread-3 MyObject name: two, thread: Thread-2 MyObject name: one, thread: Thread-1 MyObject name: three, thread: Thread-3 MyObject name: one, thread: Thread-1 MyObject name: two, thread: Thread-2 MyObject name: three, thread: Thread-3 MyObject name: one, thread: Thread-1 MyObject name: two, thread: Thread-2 MyObject name: three, thread: Thread-3 MyObject name: three, thread: Thread-3 MyObject name: one, thread: Thread-1 MyObject name: two, thread: Thread-2
The above output shows that a ThreadLocal#get method returns the same instance of MyObject which was 'set' in the same thread. The main advantage is: we don't have to pass around the instance of the target object throughout the execution lifetime of a thread, instead we can statically access it via ThreadLocal.get() method anywhere. Think of a counterpart Singleton object whose scope is the whole application. ThreadLocal's scope, on the other hand, is limited to current thread only.
Example ProjectDependencies and Technologies Used:
|