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

How do I create a ThreadLocal variable

The following code shows how to create a ThreadLocal variable:

private ThreadLocal myThreadLocal = new ThreadLocal();

Copy the code

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

How do I access a ThreadLocal variable

Once a ThreadLocal variable has been created, you can set a value to be saved using the following code:

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

Copy the code

Values stored in a ThreadLocal variable can be read using the following methods:

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

Copy the code

The get() method returns an Object, and the set() Object requires an argument of type Object.

Specify generic types for ThreadLocal

We can create a ThreadLocal object that specifies a generic type, so we don’t need to cast the value returned using the get() method every time. An example of a ThreadLocal specifying a generic type is shown below:

private ThreadLocal myThreadLocal = newThreadLocal< String> (a);

Copy the code

Now we can only store String values into ThreadLocal objects.

And we don’t need casts to get values from ThreadLocal.

How do I initialize the value of a ThreadLocal variable

Since a value set in a ThreadLocal object can only be accessed by the thread that sets it, a thread cannot use the set() method to store an initial value on a ThreadLocal object that can be accessed by all threads.

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

private ThreadLocal myThreadLocal = newThreadLocal< String> () {



    @Override

    protected String initialValue(a) {

        return "This is the initial value";

    }



};

Copy the code

A complete example of ThreadLocal

Here is a complete example of an executable ThreadLocal:

public class ThreadLocalExample {



    public static class MyRunnable implements Runnable {



        private ThreadLocal threadLocal = new ThreadLocal();



        @Override

        public void run(a) {

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

    }



}

Copy the code

The above example creates an instance of MyRunnable and passes it as a parameter to both threads. The two threads execute the run() method separately, and each holds different values on the ThreadLocal instance. If they are not accessing a ThreadLocal object and the set() method called is synchronized, the second thread overwrites the value set by the first thread. However, because they access a 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. Unlike a ThreadLocal, where each thread has its own value, InheritableThreadLocal allows a thread and all child threads created by that thread to access its saved value.

The last

Private letter reply data to get a line of big factory Java interview summary + Alibaba Taishan manual + the knowledge points learning thinking guide + a 300 page PDF document Java core knowledge points summary!

These are some of the things that the interviewer should ask during the interview. These include basics, Java collections, JVMS, multi-threaded concurrency, Spring principles, microservices, Netty and RPC, Kafka, diaries, design patterns, Java algorithms, databases, Zookeeper, distributed caching, data structures, and more.