美文网首页
Android: 理解ThreadLocal的工作原理

Android: 理解ThreadLocal的工作原理

作者: 暮城悠然丶 | 来源:发表于2019-04-16 00:54 被阅读0次

    前言

    ThreadLocal是一个我了解后很喜欢的东西,这种思路使得变量的作用域限于线程内,并且不同线程具有不同的数据副本。典型应用场景即Looper,每个线程有且只有一个Looper,同时,不同线程对应不同的Looper,而Handler在创建时,就可以获得当前线程的Looper,使得回调时,也能切换回该线程。

    新建对象

    在使用ThreadLocal时,需要新建对象:

    //ActivitayThread中也使用了ThreadLocal
        private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
    

    ThreadLocal 是一个泛型类,并且就该类本身只有有限的几个方法,同时还有两个静态内部类,可以看出,看懂get和set方法的情况下,基本就可以了解ThreadLocal的工作原理,已添加注释解析,如下所示。

    
        private final int threadLocalHashCode = nextHashCode();
    
     
        private static AtomicInteger nextHashCode =
            new AtomicInteger();
    
    
        private static final int HASH_INCREMENT = 0x61c88647;
    
        private static int nextHashCode() {
            return nextHashCode.getAndAdd(HASH_INCREMENT);
        }
    
    
        protected T initialValue() {
            return null;
        }
    
    
        public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
            return new SuppliedThreadLocal<>(supplier);
        }
    
    
        public ThreadLocal() {
        }
    
    
        public T get() {
            Thread t = Thread.currentThread();
            ThreadLocalMap map = getMap(t);
            if (map != null) {
                //获取对应的value
                ThreadLocalMap.Entry e = map.getEntry(this);
                if (e != null) {
                    @SuppressWarnings("unchecked")
                    T result = (T)e.value;
                    return result;
                }
            }
            //懒加载,未设置过值时会调用该方法,初始化map添加该TreadLocal的一对Key:Value Value为null
            return 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;
        }
    
    
        public void set(T value) {
            //获取当前线程以及对应的map
            Thread t = Thread.currentThread();
            ThreadLocalMap map = getMap(t);
            if (map != null)
              //把当前ThreadLocal作为key
                map.set(this, value);
            else
                //初始化
                createMap(t, value);
        }
    
    
         public void remove() {
             ThreadLocalMap m = getMap(Thread.currentThread());
             if (m != null)
                 m.remove(this);
         }
    
        //每个线程里都保存着一个ThreadLocal.ThreadLocalMap的变量,由ThreadLocalMap维护ThreadLocal的值
        ThreadLocalMap getMap(Thread t) {
            return t.threadLocals;
        }
    
        void createMap(Thread t, T firstValue) {
            t.threadLocals = new ThreadLocalMap(this, firstValue);
        }
    
    
        static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
            return new ThreadLocalMap(parentMap);
        }
    
    
        T childValue(T parentValue) {
            throw new UnsupportedOperationException();
        }
    
        static final class SuppliedThreadLocal<T> extends ThreadLocal<T> {
            //...
        }
        static class ThreadLocalMap { {
            //...
        }
    

    每个Thread都会持有一个ThreadLocalMap,前面提到这是ThreadLocal的一个内部类,这是一个只用来存放ThreadLocal的HashMap类,类中维护了一个table数组,并且该类还有一个静态内部类:Entry,Entry继承于WeakReference,有一个value的字段,WeakReference持有的ThreadLocal对象当做key,value则是对应ThreadLocal的值,该类比较长,这里只给出相关代码。

        static class ThreadLocalMap {
            //...
            /**
             * The table, resized as necessary.
             * table.length MUST always be a power of two.
             */
            private Entry[] table;
    
            /**
             * 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;
                }
            }
          //...
          /**
             * Construct a new map initially containing (firstKey, firstValue).
             * ThreadLocalMaps are constructed lazily, so we only create
             * one when we have at least one entry to put in it.
             */
            ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
                table = new Entry[INITIAL_CAPACITY];
                int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
                table[i] = new Entry(firstKey, firstValue);
                size = 1;
                setThreshold(INITIAL_CAPACITY);
            }
      }
    

    当创建一个ThreadLocal变量并且给它做get,set操作时,其实也是操作的ThreadLocalMap,所以接下来我们还需要看一下ThreadLocalMap这两个比较重要的方法,代码中直接插入注释解析。

            /**
             * Get the entry associated with key.  This method
             * itself handles only the fast path: a direct hit of existing
             * key. It otherwise relays to getEntryAfterMiss.  This is
             * designed to maximize performance for direct hits, in part
             * by making this method readily inlinable.
             *
             * @param  key the thread local object
             * @return the entry associated with key, or null if no such
             */
            //通过hashCode 与 当前数组的最大下标做与逻辑,直接得到目标下标。
            //判断与Key是否相等,不相等说明发生过Hash碰撞,ThreadLocalMap是开地址法,直接存入下一个空的区域。
            //无法直接探测到的全部交由getEntryAfterMiss方法去处理
            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);
            }
    
            /**
             * Version of getEntry method for use when key is not found in
             * its direct hash slot.
             *
             * @param  key the thread local object
             * @param  i the table index for key's hash code
             * @param  e the entry at table[i]
             * @return the entry associated with key, or null if no such
             */
            //主要是遍历冲突后的空间里是否能找到和key相等的ThreadLocal,当遇到null时,会去删除该位置的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;
            }
    
            /**
             * Expunge a stale entry by rehashing any possibly colliding entries
             * lying between staleSlot and the next null slot.  This also expunges
             * any other stale entries encountered before the trailing null.  See
             * Knuth, Section 6.4
             *
             * @param staleSlot index of slot known to have null key
             * @return the index of the next null slot after staleSlot
             * (all between staleSlot and this slot will have been checked
             * for expunging).
             */
            //删除当前位置的Entry以后会遍历该位置后的空间,确认是否是因为Hash冲突而后移了存储位置,将其纠正回原位。
            //同时如果该Entry引用的ThreadLocal也已经被释放的话,删除该位置的值,直到下一个位置为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;
            }
    
    
    

    理解get方法以后,set方法也很一目了然:

    
            /**
             * 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();
                    //线性探测后如果该位置有值,且key相等,则直接覆盖value
                    if (k == key) {
                        e.value = value;
                        return;
                    }
                    //ThreadLocal已经被释放,且存在hash冲突或者已经平移过几位,一次性向前整理所有无用的Entry,并替换值
                    if (k == null) {
                        replaceStaleEntry(key, value, i);
                        return;
                    }
                }
                //新建一个Entry,同时如果已经存入的Entry数量超过threshold,会扩大table容量,删除已经释放TreadLocal的Entry
                tab[i] = new Entry(key, value);
                int sz = ++size;
                if (!cleanSomeSlots(i, sz) && sz >= threshold)
                    rehash();
            }
            /**
             * Re-pack and/or re-size the table. First scan the entire
             * table removing stale entries. If this doesn't sufficiently
             * shrink the size of the table, double the table size.
             */
            private void rehash() {
                expungeStaleEntries();
    
                // Use lower threshold for doubling to avoid hysteresis
                if (size >= threshold - threshold / 4)
                    resize();
            }
            /**
             * Replace a stale entry encountered during a set operation
             * with an entry for the specified key.  The value passed in
             * the value parameter is stored in the entry, whether or not
             * an entry already exists for the specified key.
             *
             * As a side effect, this method expunges all stale entries in the
             * "run" containing the stale entry.  (A run is a sequence of entries
             * between two null slots.)
             *
             * @param  key the key
             * @param  value the value to be associated with key
             * @param  staleSlot index of the first stale entry encountered while
             *         searching for key.
             */
            private void replaceStaleEntry(ThreadLocal<?> key, Object value,
                                           int staleSlot) {
                Entry[] tab = table;
                int len = tab.length;
                Entry e;
    
                // Back up to check for prior stale entry in current run.
                // We clean out whole runs at a time to avoid continual
                // incremental rehashing due to garbage collector freeing
                // up refs in bunches (i.e., whenever the collector runs).
                int slotToExpunge = staleSlot;
                //向前查找过期值,找到最前的一个不为Null但是过期的值,也有可能是staleSlot
                for (int i = prevIndex(staleSlot, len);
                     (e = tab[i]) != null;
                     i = prevIndex(i, len))
                    if (e.get() == null)
                        slotToExpunge = i;
    
                // Find either the key or trailing null slot of run, whichever
                // occurs first
                for (int i = nextIndex(staleSlot, len);
                     (e = tab[i]) != null;
                     i = nextIndex(i, len)) {
                    ThreadLocal<?> k = e.get();
    
                    // If we find key, then we need to swap it
                    // with the stale entry to maintain hash table order.
                    // The newly stale slot, or any other stale slot
                    // encountered above it, can then be sent to expungeStaleEntry
                    // to remove or rehash all of the other entries in run.
                    if (k == key) {
                        e.value = value;
    
                        tab[i] = tab[staleSlot];
                        tab[staleSlot] = e;
                        //将之前存在Hash冲突后平移存储的位置进行互调换,并且从该位置开始做废弃条目的清除
                        // Start expunge at preceding stale entry if it exists
                        if (slotToExpunge == staleSlot)
                            slotToExpunge = i;
                        cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
                        return;
                    }
    
                    // If we didn't find stale entry on backward scan, the
                    // first stale entry seen while scanning for key is the
                    // first still present in the run.
                    //向前查找没找到废弃Entry而向后找到时,将该位置赋值给slotToExpunge 
                    if (k == null && slotToExpunge == staleSlot)
                        slotToExpunge = i;
                }
                //之前没有存过对应的ThreadLocal在该位置上存下Entry
                // If key not found, put new entry in stale slot
                tab[staleSlot].value = null;
                tab[staleSlot] = new Entry(key, value);
                //清除其他多余的废弃条目
                // If there are any other stale entries in run, expunge them
                if (slotToExpunge != staleSlot)
                    cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
            }
    
            /**
             * Heuristically scan some cells looking for stale entries.
             * This is invoked when either a new element is added, or
             * another stale one has been expunged. It performs a
             * logarithmic number of scans, as a balance between no
             * scanning (fast but retains garbage) and a number of scans
             * proportional to number of elements, that would find all
             * garbage but would cause some insertions to take O(n) time.
             *
             * @param i a position known NOT to hold a stale entry. The
             * scan starts at the element after i.
             *
             * @param n scan control: {@code log2(n)} cells are scanned,
             * unless a stale entry is found, in which case
             * {@code log2(table.length)-1} additional cells are scanned.
             * When called from insertions, this parameter is the number
             * of elements, but when from replaceStaleEntry, it is the
             * table length. (Note: all this could be changed to be either
             * more or less aggressive by weighting n instead of just
             * using straight log n. But this version is simple, fast, and
             * seems to work well.)
             *
             * @return true if any stale entries have been removed.
             */
            //执行table数组长度的对数次数的expungeStaleEntry扫描
            private boolean cleanSomeSlots(int i, int n) {
                boolean removed = false;
                Entry[] tab = table;
                int len = tab.length;
                do {
                    i = nextIndex(i, len);
                    Entry e = tab[i];
                    if (e != null && e.get() == null) {
                        n = len;
                        removed = true;
                        i = expungeStaleEntry(i);
                    }
                } while ( (n >>>= 1) != 0);
                return removed;
            }
    
    

    至此ThreadLocal的源码基本分析完毕,每个Thread自己维持自己的ThreadLocalMap,可以有多个ThreadLocal变量,并且都访问属于自己的ThreadLocalMap,有对应值的返回值,没有的通过initialValue返回null,多线程之间互相不干扰对方的数据。

    相关文章

      网友评论

          本文标题:Android: 理解ThreadLocal的工作原理

          本文链接:https://www.haomeiwen.com/subject/lofyvqtx.html