Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 如何保證一個線程最多只有一個 Looper?深入 ThreadLocal

編輯:關於 Android 程式設計

1. 如何建立 Looper?

Looper 的構造方法為 private,因此無法直接透過構造方法建立:

private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

要在當前線程建立 Looper,需使用 Looper 的 prepare 方法,即 Looper.prepare()。如果讓我們自己來實作這個方法,該怎麼做?我們知道,Android 中一個線程最多只能有一個 Looper,若在已有 Looper 的線程中呼叫 Looper.prepare(),會拋出 RuntimeException("Only one Looper may be created per thread")。

面對這樣的需求,我們可能會想到用一個 HashMap,Key 為線程 ID、Value 為與線程關聯的 Looper,再加上同步機制來實作:

public class Looper {
    static final HashMap<Long, Looper> looperRegistry = new HashMap<Long, Looper>();
    private static void prepare() {
        synchronized (Looper.class) {
            long currentThreadId = Thread.currentThread().getId();
            Looper l = looperRegistry.get(currentThreadId);
            if (l != null) throw new RuntimeException("Only one Looper may be created per thread");
            looperRegistry.put(currentThreadId, new Looper(true));
        }
    }
    ...
}

這種做法對 Looper.class 物件加鎖,這些鎖開銷有可能造成效能瓶頸。那有沒有更好的方法?我們來看看 Android 原始碼中的 Looper:

public class Looper {
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    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));
    }
    ...
}

prepare() 方法中呼叫了 ThreadLocal 的 get 和 set,整個過程卻沒有添加同步鎖。Looper 是如何實現線程安全的?答案就藏在 ThreadLocal 裡。

2. ThreadLocal

ThreadLocal 位於 java.lang 包中,JDK 文件對它的描述是:

Implements a thread-local storage, that is, a variable for which each thread has its own value. All threads share the same ThreadLocal object, but each sees a different value when accessing it, and changes made by one thread do not affect the other threads.

大致意思是:ThreadLocal 實現了線程本地存儲。所有線程共用同一個 ThreadLocal 物件,但不同線程只能存取與自己關聯的值,一個線程的修改不影響其他線程。

可以把它理解為一塊大的存儲區,劃分為多個小存儲區,每個線程擁有屬於自己的一塊,對自己那塊的操作不會影響其他線程。對於 ThreadLocal<Looper>,每一小塊存儲區裡保存的便是與特定線程關聯的 Looper。

3. ThreadLocal 的內部實作原理

3.1 Thread、ThreadLocal 與 Values 的關係

Thread 的成員變量 localValues 代表線程特定變量,類型為 ThreadLocal.Values。由於線程特定變量可能有多個且類型不確定,所以 ThreadLocal.Values 有一個 table 成員變量,型別為 Object 陣列。這個 localValues 可以理解為二維存儲區中與特定線程相關的一列。ThreadLocal 類則像一個代理,真正操作線程特定存儲區 table 的是其內部類 Values。

3.2 set 方法

public void set(T value) {
    Thread currentThread = Thread.currentThread();
    Values values = values(currentThread);
    if (values == null) {
        values = initializeValues(currentThread);
    }
    values.put(this, value);
}
Values values(Thread current) {
    return current.localValues;
}

既然與特定線程相關,所以先取得當前線程,再取得當前線程的特定存儲(即 Thread 中的 localValues);若為空則建立一個,最後把 value 存入 values。

void put(ThreadLocal key, Object value) {
    cleanUp();
    int firstTombstone = -1;
    for (int index = key.hash & mask;; index = next(index)) {
        Object k = table[index];
        if (k == key.reference) {
            // 替換既有條目
            table[index + 1] = value;
            return;
        }
        if (k == null) {
            if (firstTombstone == -1) {
                // 填入空槽
                table[index] = key.reference;
                table[index + 1] = value;
                size++;
                return;
            }
            // 回頭替換第一個墓碑
            table[firstTombstone] = key.reference;
            table[firstTombstone + 1] = value;
            tombstones--;
            size++;
            return;
        }
        if (firstTombstone == -1 && k == TOMBSTONE) {
            firstTombstone = index;
        }
    }
}

從 put 方法可以看出,ThreadLocal 的 reference 和值都會存進 table,索引分別為 index 和 index+1。以 Looper 為例:

table[index] = sThreadLocal.reference(指向自己的一個弱引用)
table[index + 1] = 與當前線程關聯的 Looper

3.3 get 方法

public T get() {
    // 針對快速路徑做優化
    Thread currentThread = Thread.currentThread();
    Values values = values(currentThread);
    if (values != null) {
        Object[] table = values.table;
        int index = hash & values.mask;
        if (this.reference == table[index]) {
            return (T) table[index + 1];
        }
    } else {
        values = initializeValues(currentThread);
    }
    return (T) values.getAfterMiss(this);
}

先取出與線程相關的 Values,再在 table 中找到 ThreadLocal 的 reference 所在位置,然後返回下一個位置儲存的物件,即 ThreadLocal 的值——以 Looper 為例,就是與當前線程關聯的 Looper 物件。

從 set 和 get 可以看出,它們操作的都只是當前線程 localValues 中的 table 陣列,所以不同線程呼叫同一個 ThreadLocal 物件的 set 和 get 互不影響。這正是 ThreadLocal 為多線程並發問題提供的一種全新思路。

4. 背後的設計思想:Thread-Specific Storage 模式

Thread-Specific Storage 讓多個線程能以相同的「邏輯全域」存取點取得各自的線程本地物件,避免了每次存取物件的鎖定開銷。

4.1 模式的起源

errno 機制被廣泛用於一些作業系統平台,它記錄系統的最後一次錯誤碼。對於單線程程式,在全域作用域內實現 errno 效果不錯;但在多線程系統中,並發可能導致一個線程設定的 errno 被其他線程錯誤解讀。當時許多遗留庫和應用都基於單線程編寫,為了在不修改既有介面和遗留程式碼的前提下解決這個問題,Thread-Specific Storage 模式應運而生。

4.2 總體結構

Thread-Specific Storage 讓每個線程都能透過同一個邏輯全域存取點取得自己本地的物件(如 ThreadLocal.Values),既避免了鎖定開銷,又保證了線程之間的隔離。Looper 正是藉助 ThreadLocal,優雅地實現了「一個線程最多一個 Looper」的約束。

參考資料

《面向模式的軟體架構 · 卷 2:並發和聯網對象模式》

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved