Java并发编程(十)ThreadLocal

逆流者 2021年02月21日 78次浏览

ThreadLocal

ThreadLocal是 JDK包提供的,它提供了线程本地变量,也就是说创建了一个 ThreadLocal变量,那么访问这个变量的每个线程都会有这个变量的一个本地副本。当多个线程操作这个变量时,实际操作的是自己本地内存里面的变量,从而避免了线程安全问题。创建一个ThreadLocal变量后,每个线程都会复制一个变量到自己的本地内存.

在这里插入图片描述

ThreadLocal 使用示例

public class ThreadLocalTest {

    static ThreadLocal<String> localVariable = new ThreadLocal<>();

    /**
     * 打印函数
     * @param str str
     */
    static void print(String str) {
        // 打印当前线程本地内存中 localVariable 变量的值
        System.out.println(str + ":" + localVariable.get());
        // 清除当前线程本地内存中的 localVariable 变量
         localVariable.remove();
    }

    public static void main(String[] args) {
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                // 设置线程 threadA 中本地变量 localVariable 的值
                localVariable.set("threadA local variable");
                print("threadA");
                System.out.println("threadA remove after" + ":" + localVariable.get());
            }
        });

        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                // 设置线程 threadB 中本地变量 localVariable 的值
                localVariable.set("threadB local variable");
                print("threadB");
                System.out.println("threadB remove after" + ":" + localVariable.get());
            }
        });

        threadA.start();
        threadB.start();
    }
}

threadA:threadA local variable
threadB:threadB local variable
threadA remove after:null
threadB remove after:null

ThreadLocal 实现原理

看一下ThreadLocal相关的类图:
ThreadLocal相关的类图

  1. Thread类中有两个ThreadLocalMap类型变量threadLocal、inheritableThreadLocals, 初始值为null;
public class Thread implements Runnable {
	// new ThreadLocal 时使用这个, 不支持继承
	ThreadLocal.ThreadLocalMap threadLocals = null;
	// new InheritableThreadLocal 时使用这个, 支持继承
    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
}
  1. 看下ThreadLocal类中的set、get、remove方法, 都是操作的Thread.currentThread() 当前线程, 也就是说ThreadLocal类只是个工具壳, 真正保存本地变量的是具体线程的内存空间.
    下面具体分析下:
public void set(T value) {
	// (1) 获取当前线程
    Thread t = Thread.currentThread();
    // (2) 当前线程作为key, 找到对应的线程变量来设置本地属性
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
    	// (3) 如果第一次调用就创建当前线程的对应的HashMap, 也就是ThreadLocalMap
        createMap(t, value);
}

ThreadLocalMap getMap(Thread t) {
	// 这个就是当前线程的内存变量
    return t.threadLocals;
}

void createMap(Thread t, T firstValue) {
	// 创建的时候也是绑定到当前线程的内存变量
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}
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();
}

private T setInitialValue() {
	// 初始化为null
    T value = initialValue();
    // 当前线程
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
    return value;
}

protected T initialValue() {
    return null;
}
public void remove() {
	// 获取当前线程
    ThreadLocalMap m = getMap(Thread.currentThread());
    if (m != null)
        m.remove(this);
}

综上所述:

  • 每一个线程内部都维护一个threadLocals的成员变量, 类型是HashMap, key是ThreadLocal变量的this引用, value是我们使用set方法设置的值;
  • 线程只要一直不消亡, 本地变量就会一直存在, 所以在使用中, 使用完本地变量后记得 remove(删除)对应线程的本地变量, 防止出现内存溢出.

ThreadLocal 不支持继承性

看一个例子

public class ThreadLocalTest2 {

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

    public static void main(String[] args) {
        threadLocal.set("hello world");

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("child thread:" + ":" + threadLocal.get());
            }
        });

        thread.start();

        System.out.println("main thread:" + threadLocal.get());
    }
}
main thread:hello world
child thread::null

在主线程(父线程)中设置的threadLocal的值, 在子线程中是看不到的.

那怎么在子线程中访问到主线程的threadLocal 值呢? (看 InheritableThreadLocal 类)

InheritableThreadLocal 类

把上面的ThreadLocal 类改成 InheritableThreadLocal:

public class ThreadLocalTest3 {

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

    public static void main(String[] args) {
        threadLocal.set("hello world");

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("child thread:" + ":" + threadLocal.get());
            }
        });

        thread.start();

        System.out.println("main thread:" + threadLocal.get());
    }
}
main thread:hello world
child thread::hello world

示例演示完了, 想不想知道InheritableThreadLocal类怎么做到的呢?

在分析之前我们看下:

public class Thread implements Runnable {
	// new ThreadLocal 时使用这个, 不支持继承
	ThreadLocal.ThreadLocalMap threadLocals = null;
	// new InheritableThreadLocal 时使用这个, 支持继承
    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
}

下面就结合源码剖析一下:

1、首先看一下InheritableThreadLocal类的源码

public class InheritableThreadLocal<T> extends ThreadLocal<T> {
    
    protected T childValue(T parentValue) {
        return parentValue;
    }

    ThreadLocalMap getMap(Thread t) {
       return t.inheritableThreadLocals;
    }

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

InheritableThreadLocal 类继承了 ThreadLocal 并重写了三个方法;

那就看这三个方法在哪里会用到了.

后两个方法createMap(Thread t, T firstValue)和getMap(Thread t)就不做过多解释了, 和父类ThreadLocal的用法一致, 只是把使用threadLocals换成了inheritableThreadLocals而已.

从 Thread 默认构造函数看起, 因为创建子线程我们 new Thread()

public Thread(Runnable target) {
	// (1) 调用初始化方法
    init(null, target, "Thread-" + nextThreadNum(), 0);
}

private void init(ThreadGroup g, Runnable target, String name,
              long stackSize, AccessControlContext acc,
                  boolean inheritThreadLocals) {
    ...
    // (2) 获取主线程, 这里当前线程就是主线程, 因为我们是在main方法中 new Thread()
    Thread parent = currentThread();
    ...
    // (3) 如果父线程(主线程) 中inheritableThreadLocals不为空
    if (inheritThreadLocals && parent.inheritableThreadLocals != null)
    	// (4) 这里this 就是子线程, 给子线程的 inheritableThreadLocals 变量赋值
        this.inheritableThreadLocals =
            ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
    this.stackSize = stackSize;

    tid = nextThreadID();
}
static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
	// (5) 根据主线程的 ThreadLocalMap 创建一个新的 属于子线程的 ThreadLocalMap
    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) {
            	// (6) 调用重写的方法
                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++;
            }
        }
    }
}