lawrence
lawrence

Reputation: 353

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>();
        }
    }

Upvotes: 2

Views: 1909

Answers (2)

Paul Wasilewski
Paul Wasilewski

Reputation: 10372

Using final or static on a ThreadLocal variable is driven by the same thoughts like using them on any other variable.

  1. When to use final?

The final keyword is used for a variable which can be only assigned once. And in case of a global one it has to be assigned directly at declaration or in the constructor.
In case of a ThreadLocal this make in 99% cases sense. Because normally, you won't change the ThreadLocal instance you will only change the referenced Object through ThreadLocal#set(T value).

  1. When to use static?

A static variable is associated to the owning Class and not to an Object. That means all instances of a Class sharing the same static variable.
If a ThreadLocal is declared as static this ThreadLocal variable (and also the references of the ThreadLocal) is shared by all Objects of the owning Class.

Upvotes: 0

Alex Suo
Alex Suo

Reputation: 3129

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.

Upvotes: 2

Related Questions