The ThreadLocal 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 a ThreadLocal variable, then the two threads can not see each other's ThreadLocal variables.
Setting value:
Reference : https://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html
Creating a ThreadLocal
private ThreadLocal myThreadLocal = new ThreadLocal();
Accessing a ThreadLocal
Setting value:
myThreadLocal.set("A thread local value");Getting value:
String threadLocalValue = (String) myThreadLocal.get();
Initial ThreadLocal Value
private ThreadLocal myThreadLocal = new ThreadLocal<String>() { @Override protected String initialValue() { return "This is the initial value"; } };
Reference : https://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html
0 Comments