When should I use a ThreadLocal variable?
How is it used?
Since Java 8 release, there is more declarative way to initialize ThreadLocal
:
ThreadLocal local = ThreadLocal.withInitial(() -> "init value");
Until Java 8 release you had to do the following:
ThreadLocal local = new ThreadLocal(){
@Override
protected String initialValue() {
return "init value";
}
};
Moreover, if instantiation method (constructor, factory method) of class that is used for ThreadLocal
does not take any parameters, you can simply use method references (introduced in Java 8):
class NotThreadSafe {
// no parameters
public NotThreadSafe(){}
}
ThreadLocal container = ThreadLocal.withInitial(NotThreadSafe::new);
Note:
Evaluation is lazy since you are passing java.util.function.Supplier
lambda that is evaluated only when ThreadLocal#get
is called but value was not previously evaluated.