Java multithreading - ThreadLocal

ThreadLocal

ThreadLocal is provided by the JDK package. It provides thread local variables. That is, if you create a ThreadLocal variable, each thread accessing the variable will have a local copy of the variable. When multiple threads operate this variable, they actually operate the variables in their own local memory, thus avoiding thread safety problems. After creating a ThreadLocal variable, each thread copies a variable to its local memory.

public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

TheadLocal manipulation is two variables in Thread, and the initial value is null

    ThreadLocal.ThreadLocalMap threadLocals = null;
    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

The two variable types are ThreadLocalMap in the inner class that is ThreadLocal

static class ThreadLocalMap {
        static class Entry extends WeakReference<ThreadLocal<?>> {
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
            ...
        }

And ThreadLocalMap is a customized HashMap.
Its Key is ThreadLocal and Value is Object

See get method again

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();
   }
ThreadLocalMap getMap(Thread t) {
       return t.threadLocals;
   }

This is the general relationship

Keywords: JDK

Added by jsantama on Mon, 25 Nov 2019 17:37:26 +0200