android Looper/ThreadLocal分析

AtomicInteger原子操作 CAS compare and set
sun.misc.Unsafe 是提供和原生内存操作有关的包

ThreadLocal内使用了AtomicInteger做threadLocalHashCode标识

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();
    }
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) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

ThreadLocal的get和set方法,只会访问当前线程,然后对线程中的ThreadLocalMap引用进行操作,如果map为空创建map
每个thread类内部有一个ThreadLocal.ThreadLocalMap引用

ThreadLocalMap是ThreadLocal的内部静态类

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

可以看到ThreadLocalMap用ThreadLocal作为key,存入我们想要保存的值

Looper中

static final ThreadLocal sThreadLocal = new ThreadLocal();
public static void prepare() {
        prepare(true);
    }

    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

looper中的prepare就通过内部的sThreadLocal 和当前的线程绑定了

threadLocalHashCode用于模拟hash,由于hash的效率低,这里从一个magic数自增来模拟hash(HASH_INCREMENT = 0x61c88647),和tab长度(初始16)按位与来分配位置,如果冲突放入下一个索引,以这个方式来存放数据。(如果满了,会rehash)

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

你可能感兴趣的:(android Looper/ThreadLocal分析)