Prev Next

Java / Java ThreadLocal

Could not find what you were looking for? send us the question and we would be happy to answer your question.

Java ThreadLocal.

java.lang.ThreadLocal class provides thread-local variables where each thread accesses its own, independent copy of the variable.

Even when two or more threads runs the same line of code that has reference to the ThreadLocal variable, the threads cannot see any other Thread's copy of the ThreadLocal variable.

How do I create a ThreadLocal variable?

The below line illustrates the way to create a ThreadLocal Variable.

private ThreadLocal myThrLocalVariable = new ThreadLocal();

Note that the above line of code needs to be executed only once by any thread. Even when multiple threads execute the code that accesses the ThreadLocal variable, each thread will access only the value set in its own copy of ThreadLocal instance. One Thread cannot access the any other thread's value of ThreadLocal variable.

Accessing a ThreadLocal Variable.

After the ThreadLocal variable has been created or instantiated, the thread can set the value of the created ThreadLocal instance using the below snippet.

myThrLocalVariable.set("Thread A's ThreadLocal value");

The set() method accepts an Object as argument.

The thread can access the value of its ThreadLocal variable using the below code.

String thrLocalVarValue = (String) myThrLocalVariable.get();

The return type of get() method is an Object.

Generic ThreadLocal variables.

ThreadLocal is a generic class which helps eliminates the need of typecasting the value being returned by the get() method.

The below code shows the way to create a generic ThreadLocal variable.

private ThreadLocal<String> thrLocalVarValue = new ThreadLocal<String>();

Creating a generic ThreadLocal variable ensures type safety thus set() method accepts only String and get() method returns only String Object eliminating the need of manual typecasting.

Initialize ThreadLocal value for all instances/threads.

Values initialized using set() method is visible to that particular thread.

However without using set() method, we could initialize the value for all the instances of ThreadLocal object by subclassing ThreadLocal class and overriding the initialValue() method. See the below example.

private ThreadLocal threadLocalVar = new ThreadLocal<String>() {
    @Override protected String initialValue() {
        return "initialized value.";
    }
}; 

With the initial value being set, all threads will see the same value "initialized value" when calling get() method until set() method gets invoked.

Explain InheritableThreadLocal class.

The java.lang.InheritableThreadLocal class, a subclass of ThreadLocal enables inheritance of values from parent thread to all the child threads. The child thread gets the initial values for all inheritable thread-local variables for which the parent thread has values.

Good practice to follow while implementing ThreadLocal variables.
  • ThreadLocal variables may be declared as private static field.
  • ThreadLocal provides another way to implement thread safety however it is not recommended for implementing synchronization.

When should I use a ThreadLocal variable?

One of the common use is when we have a object that is not thread-safe and not want to synchronize on the object, we may use ThreadLocal to have each thread its own instance of the object.

The well known example for ThreadLocal is SimpleDateFormat which is not thread-safe and we may use ThreadLocal to have every thread its own instance of SimpleDateFormat class.

Difference between ThreadLocal class and volatile keyword in Java.

Both are completely unrelated.

The ThreadLocal class stores a variable in the Thread object of the current running thread, each thread gets its own copy of ThreadLocal instance, the ThreadLocal instances are not shared among the Threads.

Volatile keyword instructs the compiler that this variable be accessed/shared across multiple threads.

What is Thread confinement in Java?

Thread confinement refers to the practice of ensuring that data is only accessible from one thread. Such data is known as thread-local as it is specific to a single thread.

«
»
Java Multithreading

Comments & Discussions