InheritableThreadLocal 用法

前言

前面介紹過ThreadLocal用法,能夠經過threadLocal在同一個線程中進行值傳遞,可是在父子線程中就不能進行值傳遞了,由於不是同一個線程,因此對應的ThreadLocalMap是不同的bash

示例

ThreadLocal示例app

public class ThreadLocalTest {
    public static ThreadLocal<String> threadLocal = new ThreadLocal<>();

    public static String get() {
        return threadLocal.get();
    }

    public static void set(String value) {
        threadLocal.set(value);
    }

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            final int j = i;
            ThreadLocalTest.set("ye");
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + ":" + ThreadLocalTest.get());
                }
            });

            t.start();
        }
    }
}
複製代碼

結果: less

InheritableThreadLocal 示例

public class InheritableThreadLocalTest {
    public static ThreadLocal<String> threadLocal = new InheritableThreadLocal<>();

    public static String get() {
        return threadLocal.get();
    }

    public static void set(String value) {
        threadLocal.set(value);
    }

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            InheritableThreadLocalTest.set("ye");
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + ":" + InheritableThreadLocalTest.get());
                }
            });

            t.start();
        }
    }
}
複製代碼

結果: ide

解析

InheritableThreadLocal是繼承ThreadLocal
先看他set方法,set 方法是調用 ThreadLocal的set方法
public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
複製代碼

createMap調用本身重寫的函數

void createMap(Thread t, T firstValue) {
        t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
    }
複製代碼

看上面發現和ThreadLocal的createMap差很少,初始化一個ThreadLocalMap,只是賦值給了inheritableThreadLocals,而ThreadLocal賦值給了threadLocalspost

繼續看get方法,get方法也是調用ThreadLocal的get方法ui

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();
    }
複製代碼

區別在於getMap調用的是InheritableThreadLocal重寫的方法this

ThreadLocalMap getMap(Thread t) {
       return t.inheritableThreadLocals;
    }
複製代碼

由於在set的時候賦值給的是t.inheritableThreadLocals,因此取map的時候也是從t.inheritableThreadLocals取的spa

看完了set和get方法,惟一的區別就是map存取的地方不同,可卻沒有看出來其餘不一樣,只是換了一個變量而已,那他是怎麼和ThreadLocal 不同,是怎麼完成父子線程的值傳遞呢 這就要看Thread的初始化了,看Thread類的構造方法你就會看到都會調用一個init方法線程

Thread的init方法

private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc,
                      boolean inheritThreadLocals) {
        if (name == null) {
            throw new NullPointerException("name cannot be null");
        }

        this.name = name;

        Thread parent = currentThread();
        SecurityManager security = System.getSecurityManager();
        if (g == null) {
            /* Determine if it's an applet or not */ /* If there is a security manager, ask the security manager what to do. */ if (security != null) { g = security.getThreadGroup(); } /* If the security doesn't have a strong opinion of the matter
               use the parent thread group. */
            if (g == null) {
                g = parent.getThreadGroup();
            }
        }

        /* checkAccess regardless of whether or not threadgroup is
           explicitly passed in. */
        g.checkAccess();

        /*
         * Do we have the required permissions?
         */
        if (security != null) {
            if (isCCLOverridden(getClass())) {
                security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
            }
        }

        g.addUnstarted();

        this.group = g;
        this.daemon = parent.isDaemon();
        this.priority = parent.getPriority();
        if (security == null || isCCLOverridden(parent.getClass()))
            this.contextClassLoader = parent.getContextClassLoader();
        else
            this.contextClassLoader = parent.contextClassLoader;
        this.inheritedAccessControlContext =
                acc != null ? acc : AccessController.getContext();
        this.target = target;
        setPriority(priority);
        if (inheritThreadLocals && parent.inheritableThreadLocals != null)
            this.inheritableThreadLocals =
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
        /* Stash the specified stack size in case the VM cares */
        this.stackSize = stackSize;

        /* Set thread ID */
        tid = nextThreadID();
    }
複製代碼

上面的方法主要看

if (inheritThreadLocals && parent.inheritableThreadLocals != null)
            this.inheritableThreadLocals =
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
複製代碼

inheritThreadLocals 是方法的入參,看構造函數只有Thread(Runnable target, AccessControlContext acc)是false,其他的構造方法都是true,因此咱們這裏傳的是true

Thread(Runnable target, AccessControlContext acc) {
        init(null, target, "Thread-" + nextThreadNum(), 0, acc, false);
    }
複製代碼
Thread parent = currentThread();
這裏指的是咱們的main線程,由於咱們在main裏面用的是InheritableThreadLocalTest.set("ye");
因此咱們把ThreadLocalMap賦值給了inheritableThreadLocals
綜上所述會走this.inheritableThreadLocals =
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
this 爲當前new的子線程                 

接下來就要看子線程的inheritableThreadLocals是怎麼賦值了

static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
        return new ThreadLocalMap(parentMap);
    }
    
private ThreadLocalMap(ThreadLocalMap parentMap) {
            Entry[] parentTable = parentMap.table;
            int len = parentTable.length;
            setThreshold(len);
            table = new Entry[len];

            for (int j = 0; j < len; j++) {
                Entry e = parentTable[j];
                if (e != null) {
                    @SuppressWarnings("unchecked")
                    ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
                    if (key != null) {
                        Object value = key.childValue(e.value);
                        Entry c = new Entry(key, value);
                        int h = key.threadLocalHashCode & (len - 1);
                        while (table[h] != null)
                            h = nextIndex(h, len);
                        table[h] = c;
                        size++;
                    }
                }
            }
        }    
複製代碼

上述代碼很簡單,就是拿到父線程的ThreadLocalMap,而後進行復制(淺拷貝,引用複製),這樣子線程的inheritableThreadLocals就有了對應的ThreadLocalMap,這樣經過ThreadLocalMap就能夠取到和父線程一樣的值了

小結

InheritableThreadLocal 繼承ThreadLocal ,因此用法和ThreadLocal 同樣,
惟一不一樣的是ThreadLocal用的是ThreadLocal 用的是ThreadLocal.ThreadLocalMap threadLocals變量
InheritableThreadLocal用的是ThreadLocal.ThreadLocalMap inheritableThreadLocals變量
但都是ThreadLocalMap,因此get和set本質上是沒有區別的
InheritableThreadLocal之因此能夠支持父子線程直接的傳遞
是在new Thread的時候init中  複製父線程的ThreadLocalMap 到子線程的inheritableThreadLocals中
相關文章
相關標籤/搜索