1. 程式人生 > >ThreadLocal 原理解析

ThreadLocal 原理解析

handle leg alt bsp rec 使用 hang calling targe

1.對Thread local 理解

ThreadLocal 是為了解決線程間同步而創建的一個新的思路。簡單來說就是每個線程都保存一個變量副本。

如果在Thread 內部定義一個field變量,也可以解決這個問題。

這樣就需要定義一個新的Thread類,來解決這個問題。每一次一個新的變量都需要這個case,but,實際這個新的類,與thread本身並沒有關系。

所以最好有一種方式,可以解決同步的問題,並且每個thread裏面都有一份變量,但是不需要重新定義一個thread類,來集成這個功能。

ThreadLocal就是這種思路。

技術分享
public final class Looper {
    
/* * API Implementation Note: * * This class contains the code required to set up and manage an event loop * based on MessageQueue. APIs that affect the state of the queue should be * defined on MessageQueue or Handler rather than on Looper itself. For example, * idle handlers and sync barriers are defined on the queue whereas preparing the * thread, looping, and quitting are defined on the looper.
*/ private static final String TAG = "Looper"; // sThreadLocal.get() will return null unless you‘ve called prepare(). static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); private static Looper sMainLooper; // guarded by Looper.class final MessageQueue mQueue;
final Thread mThread; private Printer mLogging; /** Initialize the current thread as a looper. * This gives you a chance to create handlers that then reference * this looper, before actually starting the loop. Be sure to call * {@link #loop()} after calling this method, and end it by calling * {@link #quit()}. */ 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)); } /** * Initialize the current thread as a looper, marking it as an * application‘s main looper. The main looper for your application * is created by the Android environment, so you should never need * to call this function yourself. See also: {@link #prepare()} */ public static void prepareMainLooper() { prepare(false); synchronized (Looper.class) { if (sMainLooper != null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } } /** * Returns the application‘s main looper, which lives in the main thread of the application. */ public static Looper getMainLooper() { synchronized (Looper.class) { return sMainLooper; } } /** * Run the message queue in this thread. Be sure to call * {@link #quit()} to end the loop. */ public static void loop() { final Looper me = myLooper(); if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn‘t called on this thread."); } final MessageQueue queue = me.mQueue; // Make sure the identity of this thread is that of the local process, // and keep track of what that identity token actually is. Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); for (;;) { Message msg = queue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. return; } // This must be in a local variable, in case a UI event sets the logger Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } msg.target.dispatchMessage(msg); if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } // Make sure that during the course of dispatching the // identity of the thread wasn‘t corrupted. final long newIdent = Binder.clearCallingIdentity(); if (ident != newIdent) { Log.wtf(TAG, "Thread identity changed from 0x" + Long.toHexString(ident) + " to 0x" + Long.toHexString(newIdent) + " while dispatching to " + msg.target.getClass().getName() + " " + msg.callback + " what=" + msg.what); } msg.recycleUnchecked(); } }
Looper

Looper是android最核心的技術之一,消息機制。是整個UI層驅動的核心。它的思路如下,每個線程都可以有一個自己的消息隊列。這個隊列默認是沒有創建的,(mainthread是系統創建的。)

我們看到,這個類裏面就有

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

也就是每個線程都有一個Looper對象。具體的細節不是本文的重點,可以看本博客的其他文章。

2.ThreadLocal源碼

...\Android\sdk\sources\android-23\java\lang\ThreadLocal.java

最主要的幾個函數,我們依次分析。

public T get()
protected T initialValue()
public void set
public void remove()

先看get

2.1 get

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

既然是每個線程一個變量副本,那key作為Thread.currentThread()是最合適的。

ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

ThreadLocalMap是個什麽東西?

這個是為了ThreadLocal使用,而創建的一種hashmap。

它支持大數據量的使用,所以entry是使用weakreference的形式。所以把它作為HashMap來理解就可以了。

剩下的代碼,最難以理解的就是

map.getEntry(this)

為什麽key是this,而不是currentThread。這個後面講set的時候,可以在做分析。

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

先看map是否已經創建,如果有,設置初值,如果沒有,先創建map,然後是設置初值。

map.set(this, value);

是的,又是這個this。this就是threadlocal這個類的實例,所以看到現在也沒有發現,每個線程都有一份副本的代碼。

繼續分析ThreadLocalMap

繼續看剛才的ThreadLocal的get & set,他們都在處理threadLocals,這個東西在哪裏定義的,Thread。

What? 這跟Thread有什麽關系,ThreadLocal不是給每個線程都存一份副本嗎,關Thread什麽事情。

回到第一章裏裏面的觀點,Thread自己的local變量,才能做到沒個實例都是單獨的副本,不會存在沖突問題。

/* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;

這段代碼躺在Thread.java裏面。

也就是java編譯器的作者,把需要添加的變量,放在了Thread裏面。所以我們只要把我們的內容塞進這個map裏面,就做到了每個thread都存在這樣一個副本。

如果類庫把對於這個map的操作都封裝了,我們只需要創建自己使用的變量就可以,yes。 這個事情ThreadLocal & ThreadLocalMap已經幫我們做了

所以我們只要使用ThreadLocal就可以。我們繼續分析,把各個細節都理清楚。

3.ThreadLocalMap

3.1 get & set

繼續看ThreadLocal的get & set,我們再把細節理一遍。

ThreadLocalMap.Entry e = map.getEntry(this)
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);
        }

這個方法可以看成是hashmap的命中函數。先看hash表能否命中,沒有,就全局掃描。

所以簡單來說,就是ThreadLocal就是從ThreadLocalMap(看成是hashmap)裏面獲取存儲的值。key就是threadlocal這個類的實例。應為是線程唯一的。

同理set也是相同的方法。

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

WeakReference,使用弱引用的目的,就是app裏面,或者說進程內所有的線程都共享這個threadLocals,所以內存可能會很大。這個在註釋裏面已經說的很清楚。

3.3 table

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

可以看到table就是初始化的時候,獲得的。ThreadLocalMap創建

void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

這個是ThreadLocal的代碼,可以看到set裏面有調用的代碼。

/**
         * The initial capacity -- MUST be a power of two.
         */
        private static final int INITIAL_CAPACITY = 16;

在進行哈希值索引的時候,是需要

 int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);

也就是說它是按位取&,所以i一定<= INITIAL_CAPACITY 。並且(INITIAL_CAPACITY - 1) 是“111111”這樣的形式。

ThreadLocal 原理解析