Welcome everyone

ThreadLocal 如何绑定到当前线程

java 汪明鑫 927浏览 0评论

ThreadLocal ,线程本地存储,

一个Thread就会绑定一个ThreadLocal,用来当前线程数据的存取

只对当前线程可见,线程之间是不可见的

 

我们先从ThreadLocal的set方法来讨论:

java.lang.ThreadLocal#set

public void set(T value) {
        //获取当前线程
        Thread t = Thread.currentThread();
        //根据当前线程获取绑定的ThreadLocalMap
        ThreadLocalMap map = getMap(t);
        if (map != null)
            //set操作
            map.set(this, value);
        else
            //初始化map操作
            createMap(t, value);
    }

 

我们一个个变量、一个方法去看

先瞅一眼ThreadLocalMap

java.lang.ThreadLocal.ThreadLocalMap

ThreadlLocal的静态内部类

ThreadLocalMap还有一个静态内部类Entry

static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }

 

然后我们再来看下getMap(t)

 ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

这句代码意味着什么?

意味着线程又一个成员变量ThreadLocalMap

java.lang.Thread#threadLocals

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

 

再看这个map.set(this, value)

这个map的键就是ThreadLocal

/**
         * 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;
                }
            }
            //hash映射到的位置为空时,new 一个Entry
            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }

这个set有点类似简化版的HashMap

但是需要注意的是并没有使用拉链法/红黑树解决冲突的方式

因为key为ThreadLocal,使用了特殊的hash算法

private final int threadLocalHashCode = nextHashCode();
...
private static int nextHashCode() {
        //nextHashCode是AtomicInteger   就是对HASH_INCREMENT做一个累加
        return nextHashCode.getAndAdd(HASH_INCREMENT);
    }

 

 

再看createMap(t, value);

这个就比较简单了

 void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

 

get方法当然就是从当前线程的ThreadLocalMap中取值了

 

因此ThreadLocal之所以能够存储当前线程的数据,是通过线程持有ThreadLocal的静态内部类ThreadLocalMap来实现的

到今天才知道=-=

转载请注明:汪明鑫的个人博客 » ThreadLocal 如何绑定到当前线程

喜欢 (0)

说点什么

您将是第一位评论人!

提醒
avatar
wpDiscuz