Java 1.8 & Android Oreo 常用源码分析

Java8 ThreadLocal 源码解析

2018-08-20  本文已影响1人  没有颜色的菜

前言

ThreadLocal ,像是一个神秘的黑衣人,令人望而生畏。唯有下定决心,一探究竟,方能解开他神秘的面纱、在Android中,Handler,EventBus,ConnectionPool 等等,都曾出现它的身影

是什么东西?

看到Thread,就想到应该是与线程有关吧,其次,Local是说本地,那组合起来就是线程私有,就是说每个线程都有备份,各备份不是同一个对象

前世今生

是一个泛型类

public class ThreadLocal<T> {}

源码解析

属性

nextHashCode 是获取 hashcode 值,HASH_INCREMENT 初始值为0x61c88647,nextHashCode()函数每次调用增加增量获取下一个值,大家可以好好看看Atomic的实现,以及底层Unsafe的语义

    private final int threadLocalHashCode = nextHashCode();

    /**
     * The next hash code to be given out. Updated atomically. Starts at
     * zero.
     */
    private static AtomicInteger nextHashCode =
        new AtomicInteger();

    /**
     * The difference between successively generated hash codes - turns
     * implicit sequential thread-local IDs into near-optimally spread
     * multiplicative hash values for power-of-two-sized tables.
     */
    private static final int HASH_INCREMENT = 0x61c88647;

    /**
     * Returns the next hash code.
     */
    private static int nextHashCode() {
        return nextHashCode.getAndAdd(HASH_INCREMENT);
    }

函数

初始值函数

    protected T initialValue() {
        return null;
    }

set ,将值拷贝到当前线程,使用ThreadLocalMap,这是一个内部类,要了解ThreadLocal,这个类是不得不了解的

    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 getMap(Thread t) {
        return t.threadLocals;
    }

一探ThreadLocalMap,前方高能,他是一个静态内部类,类似于WeakHashMap,只不过他没有WeakHashMap那么强大,没有Map那么多的接口,不过作为一个内部类,只需要为ThreadLocal服务就可以了,这一条可以在EffectiveJava里找到,废话不多说,看一下他的Entry,继承自WeakReference,关于WeakReference,又可以花大篇幅来介绍了,不过现在暂时不说了,你只要记住当发生GC的时候,WeakReference的对象都会被回收。同样内部也是用Entry数组,默认大小为16,set 函数需要注意的是如何处理哈希碰撞的问题,这里扯一下,处理哈希碰撞的如HashMap使用了拉链法,而这里使用了简单的开发地址法,具体来说就是如果发生了碰撞,就位置就+1,一直到有位置。

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;

        /**
         * The number of entries in the table.
         */
        private int size = 0;

        /**
         * The next size value at which to resize.
         */
        private int threshold; // Default to 0
        }
        // set 函数,同样也是使用key的hashcode 与 len-1的
        // 与值
        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();
        }

最重要的 get 函数,我们需要记住的是,每个线程有一个ThreadLocalMap,每个Map可以放很多个值,也就是不用的ThreadLocal对象。如果Get 不到数据的话,就会调用InitialValue函数进行赋值,所以有时候我们会重写这个函数,以保证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();
    }

由于使用了WeakReference,可能会存在值丢失,那ThreadLocalMap又是怎么处理这种情况呢?首先自然是处理hash碰撞的问题,通过nextIndex来遍历,其中如果出现某个key获取不到的话,就会执行
expungeStaleEntry(i) 删除旧的entry,具体的做法就是删除这个entry,以及之后出现为空的所有entry

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

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

小结

一个 ThreadLocal 竟包含了如此多的知识,当你熟读各种源码的时候,各种设计模式,各种细节,作者实现的非常有借鉴意义,理解了这样的源码,在今后的项目中使用类似的,便可以知其然知其所以然,做到各种框架的深度定制,甚至实现自己的框架!

欢迎讨论~

上一篇下一篇

猜你喜欢

热点阅读