[fundamentals of java high performance programming] - thread closure and ThreadLocal source code analysis

Posted by tylerdurden on Wed, 12 Jan 2022 19:59:27 +0100

Thread closure concept

When multiple threads access shared variable data, it will involve the problem of data synchronization between threads. If the data is enclosed in their own threads, there is no need to synchronize, and there will be no thread safety problem. This technique of avoiding synchronization by enclosing data in threads is called thread closure.

There are many ways to realize thread closure, such as

  • ad-hoc thread closure
  • local variable
  • ThreadLocal

ThreadLocal parsing

ThreadLocal is an api provided by jdk to implement thread closure. It is located in Java Under the package.

ThreadLocal can be easily understood as "local Thread" by its name. In fact, ThreadLocal is not a Thread, but a local variable of Thread.

ThreadLocal is a special variable in Java. It is a thread level variable. Each thread has a ThreadLocal, that is, each thread has its own independent variable. The competitive conditions have been completely eliminated. It is an absolutely safe variable in the concurrent mode.

Opening the Thread source code, we can see that a ThreadLocalMap is maintained inside each Thread object. Such a ThreadLocal Map can store several threadlocales.

Definition of ThreadLocal class

Next, go to the ThreadLocal class to view its class declaration in the source code:

/**
 * This class provides thread-local variables.  These variables differ from
 * their normal counterparts in that each thread that accesses one (via its
 * {@code get} or {@code set} method) has its own, independently initialized
 * copy of the variable.  {@code ThreadLocal} instances are typically private
 * static fields in classes that wish to associate state with a thread (e.g.,
 * a user ID or Transaction ID).
 *
 * <p>For example, the class below generates unique identifiers local to each
 * thread.
 * A thread's id is assigned the first time it invokes {@code ThreadId.get()}
 * and remains unchanged on subsequent calls.
 * <pre>
 * import java.util.concurrent.atomic.AtomicInteger;
 *
 * public class ThreadId {
 *     // Atomic integer containing the next thread ID to be assigned
 *     private static final AtomicInteger nextId = new AtomicInteger(0);
 *
 *     // Thread local variable containing each thread's ID
 *     private static final ThreadLocal&lt;Integer&gt; threadId =
 *         new ThreadLocal&lt;Integer&gt;() {
 *             &#64;Override protected Integer initialValue() {
 *                 return nextId.getAndIncrement();
 *         }
 *     };
 *
 *     // Returns the current thread's unique ID, assigning it if necessary
 *     public static int get() {
 *         return threadId.get();
 *     }
 * }
 * </pre>
 * <p>Each thread holds an implicit reference to its copy of a thread-local
 * variable as long as the thread is alive and the {@code ThreadLocal}
 * instance is accessible; after a thread goes away, all of its copies of
 * thread-local instances are subject to garbage collection (unless other
 * references to these copies exist).
 *
 * @author  Josh Bloch and Doug Lea
 * @since   1.2
 */
public class ThreadLocal<T> 

This class provides thread local variables. These variables are different from their normal correspondence, because each thread (through its get or set method) has its own independently initialized copy of the variables. ThreadLocal instances are typically private static fields (for example, user ID or transaction ID) in the class that you want to associate the state with the thread.

For example, the following class generates a unique identifier local to each thread. The ID of the thread is the first time ThreadID is called Get() is allocated and remains unchanged in subsequent calls.

 import java.util.concurrent.atomic.AtomicInteger;

 public class ThreadId {
     // Atomic integer containing the next thread ID to be assigned
     private static final AtomicInteger nextId = new AtomicInteger(0);

     // Thread local variable containing each thread's ID
     private static final ThreadLocal<Integer> threadId =
         new ThreadLocal<Integer>() {
             @Override protected Integer initialValue() {
                 return nextId.getAndIncrement();
         }
     };

     // Returns the current thread's unique ID, assigning it if necessary
     public static int get() {
         return threadId.get();
     }
 } 

As long as the thread survives and the ThreadLocal instance can be accessed, each thread saves an implicit reference to its thread local variable copy; After the thread disappears, all copies of the local instance of the thread will be garbage collected (unless there are other references to these copies).

Methods provided in ThreadLocal class

Construction method

    /**
     * Creates a thread local variable.
     * @see #withInitial(java.util.function.Supplier)
     */
    public ThreadLocal() {
    }

Only one null parameter construction method is provided in ThreadLocal. The usage is as follows:

ThreadLocal<T> var = new ThreadLocal<T>();

Member method

1. withInitial(Supplier<? extends S> supplier)
Create thread local variable

    /**
     * Creates a thread local variable. The initial value of the variable is
     * determined by invoking the {@code get} method on the {@code Supplier}.
     *
     * @param <S> the type of the thread local's value
     * @param supplier the supplier to be used to determine the initial value
     * @return a new thread local variable
     * @throws NullPointerException if the specified supplier is null
     * @since 1.8
     */
    public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
        return new SuppliedThreadLocal<>(supplier);
    }

2. get()
Returns the value in a copy of the thread local variable of the current thread. If the variable does not have the value of the current thread local variable, it is first initialized to the value returned by calling the initialValue() method.

    /**
     * Returns the value in the current thread's copy of this
     * thread-local variable.  If the variable has no value for the
     * current thread, it is first initialized to the value returned
     * by an invocation of the {@link #initialValue} method.
     *
     * @return the current thread's value of this thread-local
     */
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

3. set(T value)
Sets a copy of the thread local variable of the current thread to the specified value. Most subclasses will not need to override this method, relying only on the initialValue() method to set the value of the thread's local value.

    /**
     * Sets the current thread's copy of this thread-local variable
     * to the specified value.  Most subclasses will have no need to
     * override this method, relying solely on the {@link #initialValue}
     * method to set the values of thread-locals.
     *
     * @param value the value to be stored in the current thread's copy of
     *        this thread-local.
     */
    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

4. remove()
Deletes the value of the current thread for this thread local variable. If this thread local variable is followed by the current thread's read, its value is reinitialized by calling its initialValue() method. This may result in multiple calls to the initialValue method in the current thread.

    /**
     * Removes the current thread's value for this thread-local
     * variable.  If this thread-local variable is subsequently
     * {@linkplain #get read} by the current thread, its value will be
     * reinitialized by invoking its {@link #initialValue} method,
     * unless its value is {@linkplain #set set} by the current thread
     * in the interim.  This may result in multiple invocations of the
     * {@code initialValue} method in the current thread.
     *
     * @since 1.5
     */
     public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     }

ThreadLocal example

public class ThreadLocalTest {
    /** threadLocal Variable, each thread has a copy, which does not interfere with each other */
    public static ThreadLocal<String> value = new ThreadLocal<>();

    /**
     * threadlocal test
     *
     * @throws Exception
     */
    public void threadLocalTest() throws Exception {

        // threadlocal thread closure example
        value.set("This is 123 for the main thread"); // Main thread settings
        String v = value.get();
        System.out.println("The value obtained by the main thread before thread 1 executes:" + v);

        new Thread(new Runnable() {
            @Override
            public void run() {
                String v = value.get();
                System.out.println("Value obtained by thread 1:" + v);
                // Set threadLocal
                value.set("This is 456 set by thread 1");

                v = value.get();
                System.out.println("After reset, the value obtained by thread 1:" + v);
                System.out.println("End of thread 1 execution");
            }
        }).start();

        Thread.sleep(5000L); // Wait for all threads to finish executing

        v = value.get();
        System.out.println("After thread 1 executes, the value obtained by the main thread:" + v);

    }

    public static void main(String[] args) throws Exception {
        new ThreadLocalTest().threadLocalTest();
    }
}

Topics: source code ThreadLocal