ThreadLocal原理分析

ThreadLocal提供了线程本地变量,也就是说如果你创建了一个ThreadLocal变量,那么访问这个变量的每个线程都会为这个变量生成一个本地副本,当多个线程操作这个变量时,实际操作的是自己本地内存里面的变量,从而避免了线程安全问题。

ThreadLocal实例

首先,我们通过一个实例来初步了解一下ThreadLocal的用法

public static void main(String[] args) throws InterruptedException {
	final ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
	threadLocal.set(1);
    Thread threadOne = new Thread(new Runnable() {
        public void run() {
            System.out.println("threadOne threadLocal before change:" + threadLocal.get());
            threadLocal.set(3);
            System.out.println("threadOne threadLocal after change:" + threadLocal.get());
            threadLocal.remove();
        }
    });
    Thread threadTwo = new Thread(new Runnable() {
        public void run() {
            System.out.println("threadTwo threadLocal before change:" + threadLocal.get());
            threadLocal.set(6);
            System.out.println("threadTwo threadLocal after change:" + threadLocal.get());
            threadLocal.remove();
        }
    });
    threadOne.start();
    threadTwo.start();
}

运行结果如下:

threadOne threadLocal before change:null
threadOne threadLocal after change:3
threadTwo threadLocal before change:null
threadTwo threadLocal after change:6

线程One和线程Two分别创建了本地内存的副本,线程One对本地内存中变量的修改并不影响线程Two本地内存中threadLocal变量的值。

注意:如果当前线程一直不消亡,本地内存中的变量会一直存在,可能会造成内存溢出,因此使用完毕后需调用remove方法删除对应线程本地内存中的变量。

ThreadLocal实现原理

ThreadLocal类结构如下,接下来我们进行逐一分析
在这里插入图片描述
在进行ThreadLocal原理分析前,需要先对Thread类中如下知识进行补充
在这里插入图片描述
Thread类中有一个threadLocals和一个inheritableThreadLocals与LocalThread相关,他们都是ThreadLocalMap类型的变量,它是一个定制化的HashMap。
默认情况下,这两个变量的值为null,只有当线程调用ThreadLocal的set/get方法时才会创建他们,ThreadLocal的set/get方法都直接或间接的调用了createMap方法去初始化这两个变量的值。其实每个线程的本地变量不是存放在ThreadLocal实例里面,而是存放在当前线程的threadLocals变量里,ThreadLocal通过set方法把值存放在调用线程的threadLocals里,再通过get方法从threadLocals中取出来使用,这就是上面说的为什么线程不消亡,必须要调用remove方法删除本地变量的原因。

  • void set(T value)
public void set(T value) {
	//获取当前线程
    Thread t = Thread.currentThread();
    //查找当前线程变量,找到则设置值为value
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
    	//第一次调用则创建本地变量,并设置值为value
        createMap(t, value);
}
ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}
void createMap(Thread t, T firstValue) {
	//初始化threadLocals
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}
  • T get()
public T get() {
	//获取当前线程
    Thread t = Thread.currentThread();
    //查找当前线程变量,找到则返回对应value
    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;
        }
    }
    //第一次调用则初始化threadLocals
    return setInitialValue();
}
//此方法和set()方法类似,只是为了避免用户重写set()方法
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;
}
  • void remove()
 public void remove() {
 	//获取当前线程threadLocals
     ThreadLocalMap m = getMap(Thread.currentThread());
     if (m != null)
     	//不为空则调用ThreadLocalMap的remove方法移除entry
         m.remove(this);
 }
private void remove(ThreadLocal<?> key) {
	//获取到当前ThreadLocalMap的entry
    Entry[] tab = table;
    int len = tab.length;
    int i = key.threadLocalHashCode & (len-1);
    //遍历移除entry
    for (Entry e = tab[i];
         e != null;
         e = tab[i = nextIndex(i, len)]) {
        if (e.get() == key) {
            e.clear();
            expungeStaleEntry(i);
            return;
        }
    }
}

InheritableThreadLocal

上面提到了Thread类的两个变量,threadLocals和inheritableThreadLocals,那么inheritableThreadLocals是起什么作用呢?
从上面的实例可以看出,ThreadLocal不支持继承,但是有没有办法让子线程可以获取到父线程的值呢,inheritableThreadLocals就是用来处理这样的问题。相对应的类就是InheritableThreadLocal,InheritableThreadLocal类继承自ThreadLocal,其作用就是让子线程能够访问父线程中的本地变量。代码如下:

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类的三个方法,getMap和createMap所操作的都是inheritableThreadLocals变量。可见,在使用InheritableThreadLocal时变量inheritableThreadLocals替代了threadLocals。

那么childValue什么时候使用呢?让我们再看看Thread的相关代码

//构造函数
public Thread(Runnable target) {
    init(null, target, "Thread-" + nextThreadNum(), 0);
}
private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc,
                      boolean inheritThreadLocals) {
    ......
	//获取当前线程
    Thread parent = currentThread();
    ......
    //inheritThreadLocals为true(实际仅有一处调用传参为false,且该方法不对外提供)
    //并且父类的inheritableThreadLocals不为空
    if (inheritThreadLocals && parent.inheritableThreadLocals != null)
    	//将父线程的inheritableThreadLocals变量赋值给当前线程
        this.inheritableThreadLocals = 
        	ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
    ......
}

可以看到,当父线程inheritableThreadLocals不为null时,会使用父线程的inheritableThreadLocals变量作为参数,调用createInheritedMap方法,为当前线程inheritableThreadLocals赋值。
再来看看ThreadLocal的createInheritedMap方法做了些什么。

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) {
            	//调用重写的childValue方法
                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++;
            }
        }
    }
}

由上面的分析可得,调用InheritableThreadLocal的set/get方法设置变量时,会创建当前线程的inheritableThreadLocals变量,当父线程创建子线程时,构造函数会把父线程的inheritableThreadLocals变量赋值给子线程的inheritableThreadLocals变量。

最后,我们通过一个实例来看看子线程如何访问到父线程中的值,只需将上面实例中的ThreadLocal替换为InheritableThreadLocal即可。

public static void main(String[] args) throws InterruptedException {
    final ThreadLocal<Integer> threadLocal = new InheritableThreadLocal<Integer>();
    //父线程对threadLocal赋值
    threadLocal.set(1);
    Thread threadOne = new Thread(new Runnable() {
        public void run() {
            System.out.println("threadOne threadLocal before change:" + threadLocal.get());
            threadLocal.set(3);
            System.out.println("threadOne threadLocal after change:" + threadLocal.get());
            threadLocal.remove();
        }
    });
    Thread threadTwo = new Thread(new Runnable() {
        public void run() {
            System.out.println("threadTwo threadLocal before change:" + threadLocal.get());
            threadLocal.set(6);
            System.out.println("threadTwo threadLocal after change:" + threadLocal.get());
            threadLocal.remove();
        }
    });
    threadOne.start();
    threadTwo.start();
}

运行结果如下:

threadOne threadLocal before change:1
threadOne threadLocal after change:3
threadTwo threadLocal before change:1
threadTwo threadLocal after change:6
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值