知识图谱整理之Java基础ThreadLocal

ThreadLocal介绍

先来介绍下这个类的作用。首先这个类的操作是线程安全的,主要是用来存储线程相关的信息,存储局部变量,实现局部变量的线程隔离

主要方法介绍

get方法源码

    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();
    }
  • 这里的逻辑比较简单,调用getMap方法,ThreadLocalMap getMap(Thread t) { return t.threadLocals; },可以看到就是从Thread中取。如果不为null,则根据本身实例this,从ThreadLocalMap获取值
  • 如果为空,则调用setInitialValue方法。
setInitialValue方法源码
    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;
    }
  • 这里源码也比较简单,重点是 void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); }新建一个ThreadLocalMap

set方法源码

    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内部类

我们之前有过看HashMap的经历之后,看这个源码就比较简单了,但是注意刚开始我是以为和HashMap的实现一样,但实际上不是。先来看下Entry类。

内部Entry类源码

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

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }
  • 这里涉及到了WeakReference弱引用。弱引用是指如果这个对象没有被强引用的话,那么发生gc的时候会进行回收。另外弱引用还有ReferenceQueue会存放弱引用gc后的对象值。具体可另外阅读。
  • 还有一点注意到没有,这里没有使用链表的方式,那么是如何来处理Hash碰撞的呢

再从构造方法开始入手:

        ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
        	// private static final int INITIAL_CAPACITY = 16;
            table = new Entry[INITIAL_CAPACITY];
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            table[i] = new Entry(firstKey, firstValue);
            size = 1;
            setThreshold(INITIAL_CAPACITY);
        }
  • 其中threadLocal的threadLocalHashCode只是为了让hashCode索引更加的平均,具体什么算法原理目前不知。
  • 我们可以看到初始容量是16,阈值为private void setThreshold(int len) { threshold = len * 2 / 3; }在这中没有可以设置容量或阈值的构造方法
  • 这里还有一个构造方式参数是ThreadLocalMap我们不做详解,我没使用到过,大致看了下会产生父子关系

getEntry方法源码

        private Entry getEntry(ThreadLocal<?> key) {
            int i = key.threadLocalHashCode & (table.length - 1);
            Entry e = table[i];
            if (e != null && e.get() == key)
                return e;
            else
                return getEntryAfterMiss(key, i, e);
        }
private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
            Entry[] tab = table;
            int len = tab.length;

            while (e != null) {
                ThreadLocal<?> k = e.get();
                if (k == key)
                    return e;
                if (k == null)
                    expungeStaleEntry(i);
                else
                    i = nextIndex(i, len);
                e = tab[i];
            }
            return null;
        }
  • 在这里我们可以解除之前的疑惑,即这是如何解决Hash冲突的,其实使用的是开放寻址法,我们可以看下private static int nextIndex(int i, int len) { return ((i + 1 < len) ? i + 1 : 0); }方法
  • 这里还剩下的一个疑问是expungeStaleEntry方法的作用
expungeStaleEntry方法源码
private int expungeStaleEntry(int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;

            // expunge entry at staleSlot
            tab[staleSlot].value = null;
            tab[staleSlot] = null;
            size--;

            // Rehash until we encounter null
            Entry e;
            int i;
            for (i = nextIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = nextIndex(i, len)) {
                ThreadLocal<?> k = e.get();
                if (k == null) {
                    e.value = null;
                    tab[i] = null;
                    size--;
                } else {
                    int h = k.threadLocalHashCode & (len - 1);
                    if (h != i) {
                        tab[i] = null;

                        // Unlike Knuth 6.4 Algorithm R, we must scan until
                        // null because multiple entries could have been stale.
                        while (tab[h] != null)
                            h = nextIndex(h, len);
                        tab[h] = e;
                    }
                }
            }
            return i;
        }
  • 这段方法刚开始原理懂,但是摸不清楚,原因是我从getEntryAfterMiss进来的,摸不透什么时候key会为null。
  • 这个方法可以从remove方法开始阅读,其实就是移除当前对象,并对之后到下一个null之前的对象进行hash重定位

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();
        }
  • 这里的逻辑也比较的简单,主要不清楚的方法是replaceStaleEntry方法和rehash方法。
  • replaceStaleEntry的源码我们就不分析了,主要功能就是用来创建或替换一个
  • rehash方法源码中包含expungeStaleEntries方法和resize方法。

今日总结

今天观看了ThreadLocal的源码,虽然里面有很多方法并没有记录下来,但是主体思想大概已经了解。这里注意为了避免发生内存溢出,需要在使用完成后remove掉,虽然Entry是弱引用,但是ThreadLocal是强引用,所以如果不主动remove掉会造成内存溢出。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章