理解Java ThreadLocal

原文链接 理解Java ThreadLocal

ThreadLocal是Java提供的为每个线程存储线程独立的数据的存储方式,也就是说用ThreadLocal来保存的数据,只能被当前线程所访问,其他线程无法访问,因为只有(一个线程)当前线程能够访问,所以它是线程安全的,可以用来存储一些不能被共享的数据。

[图片上传失败...(image-4163fa-1686572135740)]

基本使用方法

ThreadLocal使用起来非常的简单,它支持泛型,可以把任意类型的数据放进ThreadLocal,一个ThreadLocal对象只能放一个对象:

ThreadLocal<String> mLocalCEOHolder = new ThreadLocal<>();
ThreadLocal<Integer> mOrdersCountHolder = new ThreadLocal<>();

mLocalCEOHolder.set("Alex Hilton");

String ceo = mLocalCEOHolder.get();

mOrdersCountHolder.set(30249);

int order = mOrdersCountHolder.get();

实现原理解析

就按上面的例子来解析它的实现原理:

  • 创建ThreadLocal对象

    先来看看它的构造方法:

/**
 * Creates a thread local variable.
 * @see #withInitial(java.util.function.Supplier)
 */
public ThreadLocal() {
}

很不幸,它的构造方法是空的,啥也没干。

  • set方法
    再来看下它的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);
}

这里先获取当前的调用线程,从其中获取一个叫做ThreadLocalMap的东西,如果它不为空就把当前对象this(ThreadLocal对象)作为key,把要存放的值作为value,放到这个ThreadLocalMap里面,如果map为空就先创建再存放。由此可以猜出ThreadLocalMap是一个Map型的数据结构,接着研究getMap和createMap,后面再详细说ThreadLocalMap。

/**
 * 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;
}


/**
 * Create the map associated with a ThreadLocal. Overridden in
 * InheritableThreadLocal.
 *
 * @param t the current thread
 * @param firstValue value for the initial entry of the map
 */
void createMap(Thread t, T firstValue) {
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}

getMap比较简单,它返回Thread对象的域对象threadLocal。createMap也很简单创建一个ThreadLocalMap对象,然后把它赋值给Thread对象的域变量。

  • get方法
    再来看看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();
}

/**
 * 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);
    return value;
}

get方法与set方法类似,同样是从当前线程取其map,从其中以当前TheadLocal对象为key来查找值,如果找到了,就返回。如果map为空,或者没找到怎么办。就用setInitialValue来初始化线程的map对象,这个与set方法是一样的,只不过用空值(null)。

  • ThreadLocalMap对象
/**
 * ThreadLocalMap is a customized hash map suitable only for
 * maintaining thread local values. No operations are exported
 * outside of the ThreadLocal class. The class is package private to
 * allow declaration of fields in class Thread.  To help deal with
 * very large and long-lived usages, the hash table entries use
 * WeakReferences for keys. However, since reference queues are not
 * used, stale entries are guaranteed to be removed only when
 * the table starts running out of space.
 */
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, Object v) {
            super(k);
            value = v;
        }
    }

    /**
     * The initial capacity -- MUST be a power of two.
     */
    private static final int INITIAL_CAPACITY = 16;

    /**
     * The table, resized as necessary.
     * table.length MUST always be a power of two.
     */
    private Entry[] table;
        
    /* other codes ... */
}

完整的就不贴了,大家可以自己去查看。简单来理解,其实它就是一个HashMap,key是对ThreadLocal对象的WeakReference,value是我们放入ThreadLocal的对象。

到这里可以总结一下ThreadLocal的原理了:数据结构是存储在线程对象里的一个Map对象中,key是ThreadLocal对象的WeakReference,值就是我们想要存放的对象。

注意:下面提到的Map的意思是Thread#threadLocals,也就是ThreadLocalMap对象

核心所在

网上面很多关于ThreadLocal的文章(如这个这个)都没有讲清楚,到底它是用什么方法来保证只有当前线程才能访问,它们说的是都是它的数据结构,这个上面已经说了。但是光有一个Map,就够了吗?Thread对象有一个Map用来存储ThreadLocal数据,但是假如Thread有公开获取此Map的方法,那跟我们使用的共享变量有什么区别?

ThreadLocal的真正核心在于它取的当前线程的Map:

  • 每次从ThreadLocal取数据也好,放数据也好,目标的Map都是当前的线程的Map
  • 线程的Map是包访问权限
  • 放数据也好,取数据也好都是从当前线程的Map里存和取

所以,ThreadLocal最关键的就是由Thread.currentThread()来保证当前线程的。线程到底是什么?线程简单来理解就是一个run方法,或者说一堆方法调用,它是一个时序的概念,是一堆按某种顺序运行的指令的集合。所以,当你调用ThreadLocal#set或者ThreadLocal#get时,在set和get方法实现里面会调用Thread.currentThread来取得调用栈所在的线程---也就是当前线程,这也就保证了,一个线程只能获取自己的Map。

另外,Map必须得与每个线程对象绑定,但又由于这个域是package作用域,只有同一个package的才能访问,所以只能从ThreadLocal里操作此Map也是相对安全的,也就是说想操作此Map只能通过ThreadLocal。当然了,如果能Hack一下,生成一个与Thread在同一个package的对象,就能够直接操作Map,也就能打破ThreadLocal的封装了,这时Map就变成可共享的了,也就失去了线程独有的特性。

典型应用

最典型的应用要数Looper类的实现。

Looper的作用是帮助线程创建并运行一个消息循环(MessageQueue),很显然,一个线程有且只能有一个,那么ThreadLocal是最佳的方案。

Android当中的实现

与标准的Java的实现原理是一样的,都是把Map当作Thread的一个域,package作用域,ThreadLocal作为key, 里面的值作value。

只不过Map的具体实现略有不同。

原创不易,打赏点赞在看收藏分享 总要有一个吧

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,295评论 6 512
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,928评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,682评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,209评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,237评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,965评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,586评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,487评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,016评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,136评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,271评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,948评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,619评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,139评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,252评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,598评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,267评论 2 358

推荐阅读更多精彩内容