Handler

Android Handler机制1--ThreadLocal

2018-08-14  本文已影响0人  凯玲之恋

移步Android Handler机制详解

本片文章的主要内容如下:

  • 1、Java中的ThreadLocal
  • 2、 Android中的ThreadLocal
  • 3、Android 面试中的关于ThreadLocal的问题
  • 4、ThreadLocal的总结

Java中的ThreadLocal和Android中的ThreadLocal的源代码是不一样的

使用

public class ThreadLocalTest {
    private static ThreadLocal<String> sLocal = new ThreadLocal<>();
    private static ThreadLocal<Integer> sLocal2 = new ThreadLocal<>();

    public static void main(String[] args) {
        List<Thread> threads = new ArrayList<>();

        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    String threadName = Thread.currentThread().getName();
                    System.out.println("thread name " + threadName);
                    sLocal.set(threadName);
                    sLocal2.set(Integer.parseInt(threadName) + 10);
                    try {
                        Thread.sleep(500 * Integer.parseInt(threadName));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println("thread name " + threadName + " ---local " + sLocal.get() + " ---local " + sLocal2.get());
                }
            });
            threads.add(thread);
            thread.setName(i + "");
            thread.start();
        }
    }

}

1 Java中的ThreadLocal

1.1 ThreadLocal的前世今生

1.2 ThreadLocal类简介

1.2.1 Java源码描述

1.2.2 ThreadLocal类结构

5713484-d89c4a36ff46b0be.png

ThreadLocal的结构图:


5713484-25b7d58cc48916c7.png

1.2.3 ThreadLocal常用的方法

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

代码流程很清晰:

//ThreadLocal.java
    /**
     * 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.java
    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;

我们总结一下:

1.2.3.2 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)
                return (T)e.value;
        }
        return setInitialValue();
    }
/**
     * Variant of set() to establish initialValue. Used instead
     * of set() in case user has overridden the set() method.
     *
     * @return the initial value
     */
    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;
    }

代码很清晰,通过createMap来创建ThreadLocalMap对象,前面set(T)方法里面的ThreadLocalMap也是通过createMap来的,我们看看createMap具体实现:

/**
     * Create the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * @param t the current thread
     * @param firstValue value for the initial entry of the map
     * @param map the map to store.
     */
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

1.2.3.3

remove()方法

         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);

1.3 内部类ThreadLocalMap

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

1.3.1 存储结构

/**
         * The table, resized as necessary.
         * table.length MUST always be a power of two.
         */
        private Entry[] table;
/**
 * The next size value at which to resize.
 */
private int threshold; // Default to 0

/**
 * Set the resize threshold to maintain at worst a 2/3 load factor.
 */
private void setThreshold(int len) {
    threshold = len * 2 / 3;
}

从上面代码可以看出,加载因子设置为2/3。即每次容量超过设定的len2/3时,需要扩容。

1.3.2 存储Entry对象

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

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

看下代码:

/**
         * 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;
                }
                //和HashMap不一样,因为Entry key 继承了所引用,所以会出现key是null的情况!所以会接着在replaceStaleEntry()重新循环寻找相同的key
                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

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


       /**
         * Increment i modulo len.
         */
        private static int nextIndex(int i, int len) {
            return ((i + 1 < len) ? i + 1 : 0);
        }

1.3.2.1 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();
        }

1.3.2.2 expungeStaleEntries()与expungeStaleEntry()方法

/**
         * Expunge all stale entries in the table.
         */
        private void expungeStaleEntries() {
            Entry[] tab = table;
            int len = tab.length;
            for (int j = 0; j < len; j++) {
                Entry e = tab[j];
                if (e != null && e.get() == null)
                    expungeStaleEntry(j);
            }
        }

expungeStaleEntries()方法很简单,主要是遍历table,然后调用expungeStaleEntry(),下面我们来主要讲解下这个函数expungeStaleEntry()函数。

1.3.2.3 expungeStaleEntry()方法

ThreadLocalMap中的expungeStaleEntry(int)方法的可能被调用的处理有:

expungeStaleEntry的调用.png
通过上面的图,不难看出,这个方法在ThreadLocal的set、get、remove时都会被调用
/**
         * 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).
         */
        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;
        }

1.3.3 获取Entry对象getEntry()

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

因此,需要一个函数去确认key对应的value的值,即getEntryAfterMiss()方法

1.3.3.1 getEntryAfterMiss()函数

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

ThreadLocalMap整个get过程中遇到的key为null的Entry都被会擦除,那么value的上一个引用链就不存在了,自然会被回收。set也有类似的操作。这样在你每次调用ThreadLocal的get方法去获取值或者调用set方法去设置值的时候,都会去做这个操作,防止内存泄露,当然最保险的还是通过手动调用remove方法直接移除

1.3.4 ThreadLocalMap.Entry对象

前面很多地方都在说ThreadLocalMap里面存储的是ThreadLocalMap.Entry对象,那么ThreadLocalMap.Entry独享到底是如何存储键值对的?同时有是如何做到的对ThreadLocal对象进行弱引用?

/**
         * 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;
            }
        }
5713484-fd837cb2b37254f1.png

1.4 总结

4 ThreadLocal会存在内存泄露吗

ThreadLocal实例的弱引用,当前thread被销毁时,ThreadLocal也会随着销毁被GC回收。

参考

Android Handler机制2之ThreadLocal
ThreadLocal

上一篇 下一篇

猜你喜欢

热点阅读