Java ThreadLocal

Java-ThreadLocal

参考

用途

误区

看到很多资料上都有一些误区: 即使用ThreadLocal是用于解决对象共享访问问题, 线程安全问题等. 其实不然. 另外也不存在什么对对象的拷贝, 因为实际上和线程相关的参数实际上就存储在了Thread对象中的ThreadLocalMap threadLocals里面.

正确理解

最先接触到Thread Local这个概念是使用Python的Flask框架. 该框架中有一个对象g. 文档: flask.g.
该对象可以直接用from flask import g导入. 然后可以在需要存一些需要在多个地方使用的数据时, 可以g.set(), 然后需要获取值的时候可以直接g.get(). 而比较神奇的是在多线程环境下, 每个使用到g的地方都是直接这样引用的, 但是不同线程间的数据却不会相互覆盖. 其实g对象的实现就是使用了Thread Local.

所以个人理解, ThreadLocal其实主要是为了方便提供一些可能多个线程都需要访问的数据, 但是每个线程需要独享一个这样的对象. 如果用传统的全局变量, 每个线程虽然都能访问到, 但是会发生数据覆盖的问题, 而使用Thread Local, 则可以很方便地在不传递过多参数的情况下实现一个线程对应一个对象实例. 即这个数据需要对很多线程可见(global), 但每个线程其实都拥有一个独享的该数据对象(local).

如果不使用ThreadLocal想要实现类似的功能, 其实用一个全局静态Map<Thread, Value>就可以做到. 不过ThreadLocal就是为了简化这个操作, 而且效率高, 所以直接使用ThreadLocal即可.

一个应用场景(类似flask.g对象):

  • 每个请求由一个线程处理
  • 在请求处理过程中, 有多个地方需要用到某个数据 (比如说before_request, request_handling, post_request这几个地方)

一个看起来可行的方法是直接在请求处理代码中设置一个全局变量, 但是这样不同线程就会读到/修改同一个全局变量. 这时候使用ThreadLocal就可以很好地避免这个问题, 而不用我们自己去维护一个跟线程有关的Map来根据不同的线程获取对应的数据.

ThreadLocal例子

TransactionManager类:
注意threadLocal是一个静态的ThreadLocal变量. 意味着全部的线程访问的都是同一个ThreadLocal对象.

package multithreading.threadlocal;

/**
 * Created by xiaofu on 17-11-15.
 * https://dzone.com/articles/painless-introduction-javas-threadlocal-storage
 */
public class TransactionManager {

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

    public static void newTransaction(){
        // 生成一个新的transaction id
        String id = "" + System.currentTimeMillis();
        threadLocal.set(id);
    }

    public static void endTransaction(){
        // 避免出现内存泄露问题
        threadLocal.remove();
    }

    public static String getTransactionID(){
        return threadLocal.get();
    }


}

ThreadLocalTest类:

package multithreading.threadlocal;

/**
 * Created by xiaofu on 17-11-15.
 * https://dzone.com/articles/painless-introduction-javas-threadlocal-storage
 */
public class ThreadLocalTest {

    public static class Task implements Runnable{

        private String name;

        public Task(String name){this.name = name;}

        @Override
        public void run() {
            TransactionManager.newTransaction();
            System.out.printf("Task %s transaction id: %s\n", name, TransactionManager.getTransactionID());
            TransactionManager.endTransaction();
        }
    }

    public static void main(String[] args) throws InterruptedException {

        // 在main线程先操作一下TransactionManager
        TransactionManager.newTransaction();
        System.out.println("Main transaction id: " + TransactionManager.getTransactionID());

        String taskName = "[Begin a new transaction]";
        Thread thread = new Thread(new Task(taskName));
        thread.start();
        thread.join();

        System.out.println(String.format("Task %s is done", taskName));
        System.out.println("Main transaction id: " + TransactionManager.getTransactionID());
        TransactionManager.endTransaction();

    }

}

测试结果:
重点在于在main线程调用getTransactionID()的返回值并没有因为期间有一另个Thread设置了TransactionManger中的ThreadLocal变量的值而改变.

Main transaction id: 1510730858223
Task [Begin a new transaction] transaction id: 1510730858224
Task [Begin a new transaction] is done
Main transaction id: 1510730858223

可以看出不同线程对于同一个ThreadLocal变量的操作是不会有互相影响的. 因为该ThreadLocal变量对于所有线程都是全局的, 但是其存储的数据却是和线程相关的.

原理

ThreadLoccal类的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);
    }

getMap()方法:

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

从上面代码可以看出Thread类是有一个叫threadLocals的成员的.

public
class Thread implements Runnable{
    // ... 省略 ...
    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;
    // ... 省略 ...
}

ThreadLocalMapThreadLocal的一个静态内部类:
以下仅摘了了用于理解ThreadLocal原理的代码:

/**
     * 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 table, resized as necessary.
         * table.length MUST always be a power of two.
         */
        private Entry[] table;
        

    
        /**
         * Set the value associated with key.
         *
         * @param key the thread local object
         * @param value the value to be set
         */
        private void set(ThreadLocal<?> key, Object value) {

            // We don't use a fast path as with get() because it is at
            // least as common to use set() to create new entries as
            // it is to replace existing ones, in which case, a fast
            // path would fail more often than not.

            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)]) {
                ThreadLocal<?> k = e.get();

                if (k == key) {
                    e.value = value;
                    return;
                }

                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }
    }

所以实际ThreadLocalset方法是将对象存储到了调用该ThreadLocal的线程对象的threadLocals成员中. 而该成员的类型为ThreadLocalMap. 注意ThreadLocalMapset方法, 其key的类型是任何类型的ThreadLocal对象. 所以ThreadLocalMap对象存储了ThreadLocal -> value的键值对. 因为一个线程可能使用多个ThreadLocal对象, 所以使用了ThreadLocalMap来管理这些值. 这也解释了ThreadLocalset方法中map.set(this, value);这句代码的意思.

再来看ThreadLoccal类的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();
    }

其实就是获取当先的线程, 然后得到其ThreadLocalMap类型的threadLocals对象. 然后传递this, 即用于表明当前是要取得threadLocalskey为当前这个ThreadLocal的对象.

关于内存泄露

原因在上面那篇文章说得很清楚了.
接下来说一个关于ThreadLocal.remove()方法的实践. 虽然有些情况不会造成内存泄露, 我们可以不调用ThreadLocal.remove()方法. 但是这可能会造成一些其他问题, 比如说当线程被线程池重用的时候. 如果线程在使用完ThreadLocal后没有remove, 那么很可能下次该线程再次执行的时候(可能是不同任务了), 就可能会读到一个之前设置过的值.

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

推荐阅读更多精彩内容

  • ThreadLocal提供了线程本地变量,它可以保证访问到的变量属于当前线程,每个线程都保存有一个变量副本,每个线...
    FX_SKY阅读 15,335评论 0 3
  • 概述 ThreadLocal如果单纯从名字上来看像是“本地线程"这么个意思,只能说这个名字起的确实不太好,很容易让...
    eliter0609阅读 461评论 0 0
  • Android Handler机制系列文章整体内容如下: Android Handler机制1之ThreadAnd...
    隔壁老李头阅读 7,487评论 4 30
  • 前言 ThreadLocal很多同学都搞不懂是什么东西,可以用来干嘛。但面试时却又经常问到,所以这次我和大家一起学...
    liangzzz阅读 12,333评论 14 228
  • 推荐BGM:一丝不挂 时光总有一天会将我们拆散, 可是即便如此, 我们还是要在一起。 北离很喜欢一个女孩,叫曲婷,...
    黎源大大阅读 245评论 7 1