并发利器之ThreadLocal原理剖析

今天来聊一下ThreadLocal,废话不多说直奔主题。

1、ThreadLocal是什么?

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. 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).

ThreadLocal是线程本地变量,每个线程都有一个自己的、独立初始化的变量副本。

2、为什么要用到ThreadLocal?

并发场景下,会遇到多个线程操作同一个共享变量的情况,就可能会发生线程安全问题。这种场景通常可使用加锁来解决。

ThreadLocal解决这个问题换了个思路,既然多线程操作共享变量,那我将共享变量改成线程本地变量,每个线程都有一个变量副本,自己操作自己的副本。。。 采用了空间换时间的方式,省掉了加锁产生的时间开销,实现了线程隔离

3、ThreadLocal原理

我们借助源码来看一下ThreadLocal的执行原理。

3.1 源码分析

首先,来看一下从ThreadLocal的set()方法开始说起。

/**
 * 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
    ThreadLocalMap map = getMap(t);
    if (map != null)
        // 设置到ThreadLocalMap中
        map.set(this, value);
    else
        // 创建一个ThreadLocalMap,并添加
        createMap(t, value);
}
复制代码

可以看到操作的是当前线程的ThreadLocalMap,这个ThreadLocalMap又是什么呢?

static class ThreadLocalMap {
    /**
     * The entries in this hash map extend WeakReference, using
     * its main ref field as the key (which is always a
     * ThreadLocal object).  Note that null keys (i.e. entry.get()
     * == null) mean that the key is no longer referenced, so the
     * entry can be expunged from table.  Such entries are referred to
     * as "stale entries" in the code that follows.
     */
    static class Entry extends WeakReference<ThreadLocal<?>> {
        /** The value associated with this ThreadLocal. */
        Object value;

        Entry(ThreadLocal<?> k, O
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值