Design Concept and Function of Java ThreadLocal

  • 2021-07-09 08:21:29
  • OfStack

The ThreadLocal class in Java allows us to create variables that can only be read and written by the same thread. Therefore, if a piece of code contains a reference to an ThreadLocal variable, even if two threads execute the code at the same time, they cannot access each other's ThreadLocal variable.

How to Create an ThreadLocal Variable

The following code shows how to create an ThreadLocal variable:


private ThreadLocal myThreadLocal = new ThreadLocal();

We can see that an ThreadLocal object is instantiated with this code. We only need to instantiate the object once, and we don't need to know which thread it is instantiated by. Although all threads can access the ThreadLocal instance, each thread can only access the value it sets by calling the set () method of ThreadLocal. Even if two different threads set different values on the same ThreadLocal object, they still cannot access each other's values.

How to Access ThreadLocal Variables

1 once created an ThreadLocal variable, you can set a value to be saved by the following code:


myThreadLocal.set("A thread local value " );

You can read the values stored in the ThreadLocal variable by:


String threadLocalValue = (String) myThreadLocal.get();

The get () method returns an Object object, and the set () object needs to pass in an argument of type Object.

Specify a generic type for ThreadLocal

We can create an ThreadLocal object with a specified generic type, so that we don't need to cast the value returned using the get () method every time. The following shows an example of ThreadLocal that specifies a generic type:


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

Now we can only store values of type String into ThreadLocal objects.

And we don't need to cast when we get values from ThreadLocal.

How to Initialize the Value of an ThreadLocal Variable

Because the value set in the ThreadLocal object can only be accessed by the thread that sets the value, the thread cannot save an initial value on the ThreadLocal object using the set () method, and this initial value can be accessed by all threads.

However, we can specify an initial value for an ThreadLocal object by creating a subclass of ThreadLocal and overriding the initialValue () method. As the following code shows:


private ThreadLocal myThreadLocal = new ThreadLocal<String>() {

  @Override

  protected String initialValue() {

    return "This is the initial value";

  }

};

1 complete ThreadLocal example

The following is a complete executable example of ThreadLocal:


public class ThreadLocalExample {

  public static class MyRunnable implements Runnable {


    private ThreadLocal threadLocal = new ThreadLocal();

    @Override

    public void run() {

      threadLocal.set((int) (Math.random() * 100D));

      try {

      Thread.sleep(2000);

      } catch (InterruptedException e) {


      }

      System.out.println(threadLocal.get());

    }

  }


  public static void main(String[] args) {

     MyRunnable sharedRunnableInstance = new MyRunnable();

     Thread thread1 = new Thread(sharedRunnableInstance);

     Thread thread2 = new Thread(sharedRunnableInstance);

     thread1.start();

     thread2.start();

  }

}

The above example creates an MyRunnable instance and passes it as a parameter to both threads. The two threads execute the run () method separately, and both hold different values on the ThreadLocal instance. If they are not accessing an ThreadLocal object and the invoked set () method is synchronized, the second thread overrides the value set by the first thread. However, since they are accessing an ThreadLocal object, neither thread can see the value saved by the other. That is, they access two different values.

About InheritableThreadLocal

The InheritableThreadLocal class is a subclass of the ThreadLocal class. Each thread in ThreadLocal has its own value. Unlike ThreadLocal, InheritableThreadLocal allows one thread and all child threads created by that thread to access its saved value.


Related articles: