ThreadLocal (本地线程)的实现原理

概述

ThreadLocal 会为每个线程创建一个副本,类似于线程的私有变量,仅限于这些变量互不影响的前提下;但如果传入的是共享变量,取出的还是那个共享变量,多线程并发安全问题还是要通过其他方法去解决。

ThreadLocal 只是提供了保持对象的方法和避免参数的传递,适用 ThreadLocal 的变量应该互相没有依赖关系,常用与:数据库连接、Session管理等

ThreadLocal 实现原理(jdk1.8)

ThreadLocal 的官方简介(百度翻译版)

  • 这个类提供线程局部变量。这些变量不同于正常同行,每一个线程访问一个(通过其 getset法)有自己独立的变量,初始化复制。 ThreadLocal实例通常是私有的静态字段在类希望关联状态的线程(例如,一个用户ID或交易ID)。

    例如,每个线程生成唯一的标识符。一个线程的ID分配第一次调用ThreadId.get()仍然在后续调用不变。

ThreadLocal 中所有方法

  • initialValue方法源码
/**
     * Returns the current thread's "initial value" for this
     * thread-local variable.  This method will be invoked the first
     * time a thread accesses the variable with the {@link #get}
     * method, unless the thread previously invoked the {@link #set}
     * method, in which case the {@code initialValue} method will not
     * be invoked for the thread.  Normally, this method is invoked at
     * most once per thread, but it may be invoked again in case of
     * subsequent invocations of {@link #remove} followed by {@link #get}.
     *
     * <p>This implementation simply returns {@code null}; if the
     * programmer desires thread-local variables to have an initial
     * value other than {@code null}, {@code ThreadLocal} must be
     * subclassed, and this method overridden.  Typically, an
     * anonymous inner class will be used.
     *
     * @return the initial value for this thread-local
     */
    protected T initialValue() {
        return null;
    }

initialValue 方法比较简单,初值默认是NULL,这个方法通常会被重写用来在get之前赋初值,因此是protected修饰

  • get方法以及他调用的子方法源码:
/**
     * Returns the value in the current thread's copy of this
     * thread-local variable.  If the variable has no value for the
     * current thread, it is first initialized to the value returned
     * by an invocation of the {@link #initialValue} method.
     *
     * @return the current thread's value of this thread-local
     */
    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();
    }

 /**
     * Get the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * @param  t the current thread
     * @return the map
     */
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

/* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;

/**
     * Variant of set() to establish initialValue. Used instead
     * of set() in case user has overridden the set() method.
     *
     * @return the initial value
     */
    private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            map.set(this, value);
        } else {
            createMap(t, value);
        }
        if (this instanceof TerminatingThreadLocal) {
            TerminatingThreadLocal.register((TerminatingThreadLocal<?>) this);
        }
        return value;
    }

具体讲一下 get 方法

1. 首先会获取当前线程 t,将t 的 threadLocals 变量赋值给map

2. 如果map不为空,取出map中存放的value

3. 若map为空就调用setInitialValue() 赋值,并返回该值

从上述源码可以发现,在ThreadLocal 变量存放在该线程 ThreadLocalMap类型的 threadLocals 变量内,而ThreadLocal 变量则是定义在Thread类中。其次是map中存放键值对的形式 map.set(this, value); 用调用该方法的线程作为key,保证线程和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 map = getMap(t);
        if (map != null) {
            map.set(this, value);
        } else {
            createMap(t, value);
        }
    }

和get相似,获取线程和Map;之后要么设置值,要么创建Map

  • remove源码
/**
     * Removes the current thread's value for this thread-local
     * variable.  If this thread-local variable is subsequently
     * {@linkplain #get read} by the current thread, its value will be
     * reinitialized by invoking its {@link #initialValue} method,
     * unless its value is {@linkplain #set set} by the current thread
     * in the interim.  This may result in multiple invocations of the
     * {@code initialValue} method in the current thread.
     *
     * @since 1.5
     */
     public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null) {
             m.remove(this);
         }
     }

/**
         * Remove the entry for key.
         */
        private void remove(ThreadLocal<?> key) {
            Entry[] tab = table;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);
            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                if (e.get() == key) {
                    e.clear();
                    expungeStaleEntry(i);
                    return;
                }
            }
        }

remove方法,获取散列位置再清空

  • withInitial 源码
/**
     * Creates a thread local variable. The initial value of the variable is
     * determined by invoking the {@code get} method on the {@code Supplier}.
     *
     * @param <S> the type of the thread local's value
     * @param supplier the supplier to be used to determine the initial value
     * @return a new thread local variable
     * @throws NullPointerException if the specified supplier is null
     * @since 1.8
     */
    public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
        return new SuppliedThreadLocal<>(supplier);
    }

/**
     * An extension of ThreadLocal that obtains its initial value from
     * the specified {@code Supplier}.
     */
    static final class SuppliedThreadLocal<T> extends ThreadLocal<T> {

        private final Supplier<? extends T> supplier;

        SuppliedThreadLocal(Supplier<? extends T> supplier) {
            this.supplier = Objects.requireNonNull(supplier);
        }

        @Override
        protected T initialValue() {
            return supplier.get();
        }
    }

jdk1.8中新增 ThreadLocal 的 Lambda 构造方式,代码实现如下

(代码来源:https://blog.csdn.net/Roger_CoderLife/article/details/84061412

private ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 1000);

ThreadLocal 总结

1. 内部存储数据结构是Map(ThreadLocalMap)

2. 每个线程可以有多个ThreadLocal,但每一个 ThreadLocal 只能存储一对键值,因为key用this上锁,而key不能重复

3. 在没有set之前调用get方法可能会报空指针错误,因为 initialValue() 默认初始值为null,需要重写initialValue方法,所以推荐使用 withInitial() 创建ThreadLocal


笔者水平有限,若有错误欢迎纠正

参考:https://www.cnblogs.com/dolphin0520/p/3920407.html(强烈推荐,海子的博客分析都和透彻)

          https://www.iteye.com/topic/103804

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值