ThreadLocal Java Example

ThreadLocal is a class that provides thread local variable and is used to achieve thread safety. The data stored will be accessible only by a specific thread.

java-featured-image

ThreadLocal extends Object class and provides thread restriction which is a “part” from local variable.

Creating a ThreadLocal variable

ThreadLocal threadLocalExample = new ThreadLocal();

The instantiation of the ThreadLocal object in the code above needs to done only per thread.

Just like most  classes, once you have an instance of ThreadLocal you can call methods on it. Some of the methods are:

  1. get() : returns the value in the current thread’s copy of this thread local variable
  2. initialValue() : returns the current thread’s initial value for current thread local variable
  3. remove() : removes the value from the current thread for the current thread local variable
  4. set(T value) : sets the current thread’s copy of the current thread local variable to the specified value

For more detailed information about the methods visit the original Oracle documentation.

ThreadLocal instances are private static fields (in most cases) in classes that wish to associate state with a thread




Example of implementation

public class ThreadLocalExample { 
    public static class Example implements Runnable {
        private ThreadLocal<String> example = new ThreadLocal<String>();
        // override the run() method that comes from implementing Runnable class
        @Override
        public void run() {
            try {
                System.out.println("Getting values...");
                Thread.sleep(2000);
            }
            catch (InterruptedException e) {  
                System.out.println(e);
            }  
            example.set("Just a random text that will be displayed before the remove function");
            System.out.println("Before remove: " + example.get());
            example.remove();
            System.out.println("After remove: " + example.get());
        }
    }
    public static void main(String[] args) { 
        /* EXAMPLE THAT DOES NOT HAVE TO DO ANYTHING WITH THE STATIC CLASS ABOVE main*/
        ThreadLocal<String> local = new ThreadLocal<String>(); 
        local.set("First"); 
        System.out.println("Value: " + local.get()); 
  
        local.set("Second"); 
        System.out.println("Value: " + local.get()); 

        local.remove(); 
        System.out.println("Value: " + local.get());
        /* NEW EXAMPLE THAT USES THE STATIC CLASS DECLARED ABOVE main */
        Example runnable = new Example();
        Thread thread = new Thread(runnable);
        thread.start();
    } 
}

Output

Value: First
Value: Second
Value: null
Getting values...
Before remove: Just a random text that will be displayed before the remove function
After remove: null

Breakdown

The above code shows two ways you can get it working: one is by having Runnable object and pass it to a Thread instance and then override the run() method or you can simply create a ThreadLocal instance and set the value to it and then you can get or remove it. As you can see from the example above, even though it is the same variable (local), it can contain different values. In the first case, it contains the value “First”. In the second case, it contains the value “Second”. For the other implementation, I only displayed one thread. However, every thread is on its own – meaning, if you were to create another Thread instance, say thread2, and start() it, it will act on its own and it will have nothing to do with the other Thread instance variable. To check that, you could create a ThreadLocal instance within your static class and then within the overriden run() method, you can generate a random number and pass it to the current thread using the set() method. You will see that if you call it on two or more different threads, they will all have different values.

 

 

Leave a Reply

avatar