ThreadLocal analysis of multi-threading

I. Introduction

ThreadLocal has been used in the project recently, so here is an analysis and summary of ThreadLocal.

2. What is ThreadLocal

ThreadLocal looks like a thread. In fact, it is not a Thread, but a threadlocal variable, that is, a thread local variable. Its function is very simple. It provides a copy for each thread that uses the variable, so that each thread can be independent. changes its own copy without worrying about affecting the copies corresponding to other threads.

3. Methods of ThreadLocal class

There are four main methods of ThreadLocal, which are as follows:
1. public T get();
the function of this method is to obtain the thread local variable value of the current thread.

2. protected T initialValue();
this method is in the protected scope and is designed to facilitate subclass coverage. This method is a deferred call method that is executed when the thread calls get() or set(T) for the first time, and only once. The default implementation in ThreadLocal simply returns a null.

3. public void set(T value);
this method is to set the thread local variable value of the current thread.

4. public void remove();
this method is used to remove thread local variables of the current thread, in order to reduce memory usage. In fact, when the thread ends, the local variables corresponding to the thread will be automatically garbage collected, so it is not necessary to explicitly call this method to clear the local variables of the thread, but it can speed up the speed of memory reclamation.

Fourth, the realization of thread isolation

Multi-threading means that operations on one thread cannot affect other threads. So, how does ThreadLocal maintain thread-local variables for each thread separately?
There is a static class ThreadLocalMap in ThreadLocal with the following code:

        /**
         * The entries in this hash map extend WeakReference, using
         * its main ref field as the key (which is always a
         * ThreadLocal object).  Note that null keys (i.e. entry.get()
         * == null) mean that the key is no longer referenced, so the
         * entry can be expunged from table.  Such entries are referred to
         * as "stale entries" in the code that follows.
         */
        static class Entry extends WeakReference<ThreadLocal> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal k, Object v) {
                super(k);
                value = v;
            }
        }

The Entry in the above code is dedicated to storing threads and their thread-local variables. Each thread's ThreadLocal is used as the key, and the corresponding thread-local variables are stored in the map as values.
Then, when each thread obtains its own thread-local variable, it only needs to use the current ThraLocal as the key to obtain the local variable of the current thread.

Misunderstanding

When I first started to understand threadLocal, I saw several articles on the Internet saying that ThreadLocal can solve the problem of concurrent access to shared objects. Actually, this is a misunderstanding.
The following content is helpful for understanding ThreadLocal by referring
to
:
First of all, ThreadLocal is not used to solve the problem of multi-threaded access to shared objects. In general, the object to the thread through ThreadLocal.set() is used by the thread itself The object that other threads do not need to access, nor can it be accessed. Different objects are accessed in each thread.

In addition, it is said that ThreadLocal enables each thread to maintain an independent object, not through ThreadLocal.set(), but through the operation of the new object in each thread to create an object, each thread creates one, Not a copy or a duplicate of something. Save the reference of the newly created object to a map of each thread through ThreadLocal.set(). Each thread has such a map. When ThreadLocal.get() is executed, each thread takes it out from its own map The objects put in, so the objects in their own threads are taken out, and the ThreadLocal instance is used as the key of the map.

If the thing entered by ThreadLocal.set() is the same object shared by multiple threads, then ThreadLocal.get() of multiple threads still obtains the shared object itself, and there is still a concurrent access problem.

To sum up, ThreadLocal is not used to solve the problem of object shared access, but mainly provides a method for maintaining objects and a convenient object access method that avoids parameter passing.
Two points are summarized:
1. Each thread has its own ThreadLocalMap class object, which can keep the thread's own object in it, and each thread can access its own object correctly.
2. Use a shared ThreadLocal static instance as the key, save the references of different objects in the ThreadLocalMap of different threads, and then obtain the object saved by the thread through the get() method of this static ThreadLocal instance everywhere in the thread execution, avoiding the need for The trouble of passing this object as a parameter.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326457585&siteId=291194637
Recommended