lawrence lawrence - 4 months ago 9
Java Question

Should threadlocal declared as a final field

When programming using ThreadLocal class, should the field declared final?
if write code like

private ThreadLocal<String> threadLocal
and initialize it in constructor later, since the variable threadLocal reference cannot be changed any more, I guess it's equal to
private final ThreadLocal<String> threadLocal;
is this idea right?What is the difference between the following method in a multi-threading class?

public class ThreadLocalTestForMultiThread{
private ThreadLocal<String> threadLocal;
public ThreadLocalTestForMultiThread(){
threadLocal = new ThreadLocal<String>();
}
}

public class ThreadLocalTestForMultiThread{
private final ThreadLocal<String> threadLocal;
public ThreadLocalTestForMultiThread(){
threadLocal = new ThreadLocal<String>();
}
}

Answer

The bottomline is that you don't have to have final on ThreadLocal but you would most likely have not just final but also static on it.

When you are working on ThreadLocal variables, the noticeable key attribute is such variable would have an instance per thread. Also, you must provide an implementation to the initialValue() method so that the class knows how to construct a new object when needed.

Note that when you have a normal class level variable, it's implicit that such variable would have a copy as per instance. In the real world you won't have too much applications to have a ThreadLocal as per instance; and most likely you have it on the class level, that is, static. In this way it's almost sure to have it initialized in a static block or immediately.