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

Android 智能指針淺析:從 LightRefBase 到 RefBase

編輯:關於 Android 程式設計

長期以來,C++ 的記憶體管理一直令人頭痛:空指標、野指標、記憶體洩漏……C++ 工程師看到這些字眼就頭皮發麻。更麻煩的是,當程式架構龐大或複雜時,這類問題往往極難排查。

同樣是物件導向語言,Java 卻沒有這個困擾,原因在於它有 GC(垃圾回收),而 C++ 沒有。C++ 的規則是:工程師 new 出一個物件後,不需要時必須自己 delete 掉。聽起來簡單,但在真實專案裡,總有人忘記 delete,或者隨意 delete 一個仍被其他模組持有的物件,導致依賴它的地方爆出野指標錯誤。這種事情幾乎天天發生,而且很難徹底避免。

Android 除了 framework 之上以 Java 撰寫,從 native 層一路到 kernel 之上基本都是 C++,程式碼量相當可觀。它是怎麼面對上述問題的?答案是引入「智能指針」的概念。這個概念並非 Android 原創,C++ 的 boost 早就有了,Google 只是取來做了一個精簡版本。

本文聚焦於 Android 智能指針的實作。在正式讀原始碼之前,先把 C++ 的記憶體難題再往下想一層。

C++ 要求 new 與 delete 成對出現,且由工程師手動顯式執行,這對人的要求很高:你得清楚記得哪裡 new 了物件、什麼時候可以確定它不再被需要。這聽起來有點理想化。實務上更常見的情況是:我 new 了一個物件交給別的模組使用,而那個模組由別的團隊甚至別家公司維護,他們未必會及時回收。有什麼解法?

直覺的做法是專門做一個管理模組,統一負責物件的建立與銷毀。但問題馬上出現:如果有多個管理模組,怎麼保證它們之間對同一物件的引用是一致的?管理模組 A 持有引用、管理模組 B 也持有引用,兩者如何協調?這條路複雜且潛藏風險。

換個角度想,關鍵其實是引用計數——這也正是 Java GC 的基礎之一。所謂引用計數,就是這個物件被多少個地方使用:

Object a = new Object();
Object b = a;

這兩行讓 a 與 b 同時指向同一塊記憶體,此時引用計數為 2。什麼時候我們不再需要這個物件?當計數歸零的時候。於是問題轉化為:誰最清楚這個物件的引用計數?答案只能是——物件它自己。讓物件自己 delete 自己,聽起來荒謬,但 Android 的智能指針正是這麼做的。

LightRefBase

這是 Android 提供的一套輕量級方案,背後正是上面那個思路。為了讓物件能自己 delete 自己,需要一個共同基類,LightRefBase 就是這個基類。先看怎麼用它:

#include <stdio.h>
#include <utils/RefBase.h>

using namespace android;

// 目標類必須是 LightRefBase 的子類
class LightClass : public LightRefBase<LightClass> {
public:
    LightClass() {
        printf("create instance of lightclass. \n");
    }

    virtual ~LightClass() {
        printf("destory instance of lightclass. \n");
    }
};

int main(int argc, char** argv) {
    // new 一個對象,並讓指針指向它
    LightClass* ptr = new LightClass();

    // 此時還沒有顯式引用,結果應該是 0
    printf("1. Light ref count: %d. \n", ptr->getStrongCount());

    // sp<> 這樣的引用就是顯式引用,按照推理應該是 1
    sp<LightClass> ptrOut = ptr;
    printf("2. Light ref count: %d. \n", ptr->getStrongCount());

    // 代碼塊內部再弄一個指針指向這個對象
    {
        sp<LightClass> ptrInner = ptr;
        printf("3. Light ref count: %d. \n", ptr->getStrongCount());
    }

    // 代碼塊外面,內部那個指針已不存在,引用計數應該少一個
    printf("4. Light ref count: %d. \n", ptr->getStrongCount());

    // 將最後一個引用置空,睡眠兩秒,看這個對象會不會自動銷毀
    ptrOut = NULL;
    printf("5. Light ref count: %d. \n", ptr->getStrongCount());
    printf("We are going to sleep. \n");
    sleep(2);

    printf("We are going to exit. \n");
    return 0;
}

先不管細節,把它編譯成 Android 上可執行的二進位檔。Android.mk 如下:

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE_TAGS := optional
LOCAL_MODULE := lightpointer
LOCAL_SRC_FILES := lightpointer.cpp
LOCAL_SHARED_LIBRARIES := \
    libcutils \
    libutils
include $(BUILD_EXECUTABLE)

可執行檔名為 lightpointer,放在手機的 system/bin 下,執行結果如下:

vcHLw7vT0KOsyseyu8rH09C140pBVkG1xNLiy7ywoT/KudPDuty88rWlyseyuz88L3A+DQo8cD7P1tTaztLDx8C0t9bO9tK7z8K41bLFtPrC69TZYW5kcm9pZM+1zbPE2reiyfrBy8qyw7SjrMrXz8jO0sPHv7TSu8/CTGlnaHRSZWZCYXNl1eK49sDgo6y0+sLrwre+tqO6L3N5c3RlbS9jb3JlL2luY2x1ZGUvdXRpbHMvUmVmQmFzZS5oPC9wPg0KPHA+y/y1xLT6wuvI58/CPC9wPg0KPHA+PGltZyBhbHQ9"這裡寫圖片描述" src="/uploadfile/Collfiles/20160624/20160624092928665.png" title="\" />

這個類的實作相當單純,對外的方法只有三個:incStrong、decStrong、getStrongCount(就是我們前面一直在用的那個)。所有目標類都必須是它的子類。

構造器做的事情很少,只是把 mCount 初始化為 0——顧名思義,這個變數代表實際的引用數目,而 getStrongCount 就是直接把它回傳。接著看 incStrong:它呼叫 Android 工具庫中的 android_atomic_inc 把 mCount 加一,這是原子操作,考量的是執行緒安全。再看 decStrong:先用 android_atomic_dec 把 mCount 減一,再依返回值判斷是否為最後一個引用,若是就直接 delete 這個物件。這裡要注意,android_atomic_dec 的回傳值是 mCount 遞減之前的值(等同 mCount-- 的結果),所以判斷條件是 1 而不是 0。

那麼這些增減引用的方法究竟是誰在呼叫?還記得上面範例中的 sp 類嗎?就是它。它的程式碼位於 /system/core/include/utils/StrongPointer.h:

sp 內部方法很少,絕大部分都是運算子重載。先看它的構造器:

sp 是一個樣板類,目標類型為泛型。構造器中把目標物件的指標交給 m_ptr,若該指標不為空,就直接呼叫它的 incStrong 把引用計數加一。不過我們上面的範例走的不是這條路,而是 = 運算子重載:

這裡的邏輯與構造器幾乎相同,同樣呼叫 incStrong 讓計數加一,但額外考慮了「重新賦值」的情況:若原本的 m_ptr 不為空,也就是原本已有指向,必須先把舊目標的引用計數減掉,再讓它指向新物件。所以只要執行 sp ptrOut = ptr; 引用計數就加一;反過來,把指標賦值為 NULL 或其他值,目標物件的引用計數就會減少。

於是結論很清楚:只要目標類繼承 LightRefBase,並以 sp 持有它,就能實現自動銷毀,不必再手動 delete。這就是 LightRefBase——輕量級智能指針,實作與使用都清爽不繁雜,這也是它名字裡「Light」的由來。

RefBase

如果 LightRefBase 是輕量級,那少了 light 的 RefBase 就是重量級版本。Android 為什麼還需要它?考慮這樣一個場景:物件 A 持有 B 的引用,所以 B 的計數為 1;物件 B 又持有 A 的引用,所以 A 的計數也是 1。此時 A 與 B 已與外界完全脫鉤,除了彼此之外沒人引用它們,理應被回收——但兩者的計數都不為 0,用上面的方案無法處理,記憶體洩漏照樣發生。

解法是把引用分類:強引用與弱引用。強引用就是我們前面用的那種;弱引用顧名思義「力道較弱」,弱在哪裡?弱在不保證物件一定存在。回到上面的例子,如果 A 對 B 是強引用,那 B 對 A 就必須是弱引用,否則循環引用無解。物件銷毀只看強引用,不考慮弱引用——強引用歸零就立刻 delete,不管弱引用還有多少。這正是弱引用「弱」的地方:你想用的物件可能已經不在了。

那弱引用怎麼安全地使用物件?規則是:使用前必須先升級為強引用。若物件已銷毀,升級自然失敗,也就避開了物件存在與否的不確定性。

RefBase 與 LightRefBase 位於同一支檔案 /system/core/include/utils/RefBase.h,主要介面如下:

class RefBase {
public:
    void incStrong(const void* id) const;
    void decStrong(const void* id) const;
    void forceIncStrong(const void* id) const;

    //! DEBUGGING ONLY: Get current strong ref count.
    int32_t getStrongCount() const;

    class weakref_type {
    public:
        RefBase* refBase() const;
        void incWeak(const void* id);
        void decWeak(const void* id);
        // acquires a strong reference if there is already one.
        bool attemptIncStrong(const void* id);
        // acquires a weak reference if there is already one.
        // This is not always safe. see ProcessState.cpp and BpBinder.cpp
        bool attemptIncWeak(const void* id);
        int32_t getWeakCount() const;
        void printRefs() const;
        void trackMe(bool enable, bool retain);
    };

    weakref_type* createWeak(const void* id) const;
    weakref_type* getWeakRefs() const;

    typedef RefBase basetype;

protected:
    RefBase();
    virtual ~RefBase();

    //! Flags for extendObjectLifetime()
    enum {
        OBJECT_LIFETIME_STRONG = 0x0000,
        OBJECT_LIFETIME_WEAK = 0x0001,
        OBJECT_LIFETIME_MASK = 0x0001
    };

    void extendObjectLifetime(int32_t mode);

    //! Flags for onIncStrongAttempted()
    enum {
        FIRST_INC_STRONG = 0x0001
    };

    virtual void onFirstRef();
    virtual void onLastStrongRef(const void* id);
    virtual bool onIncStrongAttempted(uint32_t flags, const void* id);
    virtual void onLastWeakRef(const void* id);

private:
    friend class weakref_type;
    class weakref_impl;
    RefBase(const RefBase& o);
    RefBase& operator=(const RefBase& o);

    weakref_impl* const mRefs;
};

和 LightRefBase 一樣,RefBase 也只是目標類的基類,只是功能更完整。下面分別沿強指針與弱指針兩條線看。

sp(強指針)

很多人第一眼會以為 sp 是 smart pointer 的縮寫,其實它是 strong pointer。sp 的實作前面已經看過,主要就是運算子重載,程式碼不長。這裡著重看它與 RefBase 的協作:sp 是樣板類,目標可以是 LightRefBase 的子類,也可以是 RefBase 的子類。RefBase 同樣提供了 incStrong、decStrong 與 getStrongCount,因此在強指針這塊,兩者差異並不大。

wp(弱指針)

弱指針才是重點,畢竟它被提出來就是為了解決循環引用。wp 定義在同一支檔案中:

template <typename T>
class wp {
public:
    typedef typename RefBase::weakref_type weakref_type;

    inline wp() : m_ptr(0) { }
    wp(T* other);
    wp(const wp<T>& other);
    wp(const sp<T>& other);
    template<typename U> wp(U* other);
    template<typename U> wp(const wp<U>& other);
    template<typename U> wp(const sp<U>& other);
    ~wp();

    wp& operator = (T* other);
    wp& operator = (const wp<T>& other);
    wp& operator = (const sp<T>& other);
    template<typename U> wp& operator = (U* other);
    template<typename U> wp& operator = (const wp<U>& other);
    template<typename U> wp& operator = (const sp<U>& other);

    void set_object_and_refs(T* other, weakref_type* refs);

    // promotion to sp
    sp<T> promote() const;

    void clear();

    inline weakref_type* get_refs() const { return m_refs; }
    inline T* unsafe_get() const { return m_ptr; }

    // 比較運算子省略

private:
    template<typename Y> friend class sp;
    template<typename Y> friend class wp;

    T* m_ptr;
    weakref_type* m_refs;
};

wp 一樣是樣板類,方法看起來不少,但多為運算子重載。先看構造器:

template <typename T>
wp<T>::wp(T* other) : m_ptr(other) {
    if (other) m_refs = other->createWeak(this);
}

構造器直接把目標指標交給 m_ptr,接著呼叫 RefBase 的 createWeak:

RefBase::weakref_type* RefBase::createWeak(const void* id) const {
    mRefs->incWeak(id);
    return mRefs;
}

它轉手呼叫 weakref_type 的 incWeak 把弱引用計數加一。weakref_type 是 RefBase 的內部類:

class weakref_type {
public:
    RefBase* refBase() const;
    void incWeak(const void* id);
    void decWeak(const void* id);
    bool attemptIncStrong(const void* id);
    bool attemptIncWeak(const void* id);
    int32_t getWeakCount() const;
    void printRefs() const;
    void trackMe(bool enable, bool retain);
};

真正承載計數的是它的實作類 weakref_impl(system/core/libutils/RefBase.cpp)。這個類很長,但仔細看會發現大半都被 DEBUG_REFS 等巨集包住的除錯程式碼;release 版本中,剩下的其實只有幾行:

class RefBase::weakref_impl : public RefBase::weakref_type {
public:
    volatile int32_t mStrong;
    volatile int32_t mWeak;
    RefBase* const mBase;
    volatile int32_t mFlags;

    weakref_impl(RefBase* base)
        : mStrong(INITIAL_STRONG_VALUE)
        , mWeak(0)
        , mBase(base)
        , mFlags(0) {
    }

    void addStrongRef(const void* /*id*/) { }
    void removeStrongRef(const void* /*id*/) { }
    void renameStrongRefId(const void* /*old_id*/, const void* /*new_id*/) { }
    void addWeakRef(const void* /*id*/) { }
    void removeWeakRef(const void* /*id*/) { }
    void renameWeakRefId(const void* /*old_id*/, const void* /*new_id*/) { }
    void printRefs() const { }
    void trackMe(bool, bool) { }
};

四個成員變數才是關鍵:mStrong 是強引用計數,mWeak 是弱引用計數,mBase 指向 RefBase(實際上就是目標物件,因為目標類是 RefBase 的子類),mFlags 則用來管理物件生命週期。可以把它理解為 LightRefBase 裡 mCount 的進化版——只是這次要同時管強、弱兩套計數,一個變數不夠用,於是需要一個類來承載。

wp、RefBase、weakref_impl 三者關係有點繞,看圖會清楚很多:

wp 是操作用的指標類,內部有指向 RefBase 子類目標物件的指標,以及一個指向 weakref_impl 的指標;RefBase 內部也有一個指向 weakref_impl 的指標,用來管理引用計數;weakref_impl 才是實際的計數器,它同時持有目標物件指標,並繼承自 weakref_type。這層關係需要對照原始碼仔細體會,三言兩語只能有個大概。

接著看計數管理怎麼運作。createWeak 呼叫 incWeak:

void RefBase::weakref_type::incWeak(const void* id) {
    weakref_impl* const impl = static_cast<weakref_impl*>(this);
    impl->addWeakRef(id);
    const int32_t c __unused = android_atomic_inc(&impl->mWeak);
    ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
}

最終就是透過 android_atomic_inc 把 weakref_impl 的 mWeak 加一。再看 = 運算子重載:

template <typename T>
wp<T>& wp<T>::operator = (T* other) {
    weakref_type* newRefs = other ? other->createWeak(this) : 0;
    if (m_ptr) m_refs->decWeak(this);
    m_ptr = other;
    m_refs = newRefs;
    return *this;
}

邏輯與強指針一致:若新目標不為空就先 createWeak;若原本已有指向則先 decWeak 釋放舊的弱引用計數;最後才把新的指標寫入。

弱引用計數的管理到此說明完畢,但前面提過:弱指標使用前必須升級為強指標。怎麼升級?就是 wp 裡那個 promote():

// promotion to sp
sp<T> promote() const;
template <typename T>
sp<T> wp<T>::promote() const {
    sp<T> result;
    if (m_ptr && m_refs->attemptIncStrong(&result)) {
        result.set_pointer(m_ptr);
    }
    return result;
}

核心在 weakref_type 的 attemptIncStrong:

bool RefBase::weakref_type::attemptIncStrong(const void* id) {
    incWeak(id);

    weakref_impl* const impl = static_cast<weakref_impl*>(this);
    int32_t curCount = impl->mStrong;
    ALOG_ASSERT(curCount >= 0, "attemptIncStrong called on %p after underflow", this);

    while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {
        // 常見情況:已有強引用,直接嘗試加一
        if (android_atomic_cmpxchg(curCount, curCount + 1, &impl->mStrong) == 0) {
            break;
        }
        curCount = impl->mStrong;
    }

    if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {
        // 較少見的情況:從未有過強引用,或所有強引用都已釋放
        if ((impl->mFlags & OBJECT_LIFETIME_WEAK) == OBJECT_LIFETIME_STRONG) {
            if (curCount <= 0) {
                // 最後一個強引用已釋放,物件無法復活
                decWeak(id);
                return false;
            }
            // curCount == INITIAL_STRONG_VALUE,從未有人強引用過,嘗試原子地提升
            while (curCount > 0) {
                if (android_atomic_cmpxchg(curCount, curCount + 1, &impl->mStrong) == 0) {
                    break;
                }
                curCount = impl->mStrong;
            }
            if (curCount <= 0) {
                decWeak(id);
                return false;
            }
        } else {
            // 物件具有"延長"生命週期,可以僅從弱引用復活
            // 詢問物件實作是否同意復活
            if (!impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id)) {
                decWeak(id);
                return false;
            }
            curCount = android_atomic_inc(&impl->mStrong);
        }

        if (curCount > 0 && curCount < INITIAL_STRONG_VALUE) {
            impl->mBase->onLastStrongRef(id);
        }
    }

    impl->addStrongRef(id);

    // 修正計數:處理 INITIAL_STRONG_VALUE 的情形,且必須在多執行緒下安全
    curCount = impl->mStrong;
    while (curCount >= INITIAL_STRONG_VALUE) {
        ALOG_ASSERT(curCount > INITIAL_STRONG_VALUE,
                "attemptIncStrong in %p underflowed to INITIAL_STRONG_VALUE", this);
        if (android_atomic_cmpxchg(curCount, curCount - INITIAL_STRONG_VALUE, &impl->mStrong) == 0) {
            break;
        }
        curCount = impl->mStrong;
    }
    return true;
}

這段不短,逐層拆開看。首先,若目前強引用計數不為 0 且不等於 INITIAL_STRONG_VALUE(強引用計數的初始值),代表物件已有強引用,屬於正常情況,於是呼叫 android_atomic_cmpxchg 把 mStrong 加一。這個函式的定義是 android_atomic_cmpxchg(oldValue, newValue, addr):當 oldValue 與 addr 位址中的值相同時,就把 newValue 寫入該位址。也就是說,只有當 mStrong 仍等於我們讀到的 curCount 時才加一並回傳 0,否則回傳非 0——用這種方式確保原子性。

接著判斷 curCount 是否小於等於 0 或等於初始值,代表「所有強引用都已釋放」或「從未有人引用過」,這顯然是少數情況,進入裡面的分支。

這裡就用到了物件生命週期。生命週期定義在 RefBase 中:

//! Flags for extendObjectLifetime()
enum {
    OBJECT_LIFETIME_STRONG = 0x0000,
    OBJECT_LIFETIME_WEAK = 0x0001,
    OBJECT_LIFETIME_MASK = 0x0001
};

這些旗標存在 mFlags 中,可由使用者透過 extendObjectLifetime 手動設定:

void extendObjectLifetime(int32_t mode);

要理解生命週期的含義,看強、弱引用減少時的銷毀策略即可。先看強引用:

void RefBase::decStrong(const void* id) const {
    weakref_impl* const refs = mRefs;
    refs->removeStrongRef(id);
    const int32_t c = android_atomic_dec(&refs->mStrong);
    ALOG_ASSERT(c >= 1, "decStrong() called on %p too many times", refs);
    if (c == 1) {
        refs->mBase->onLastStrongRef(id);
        if ((refs->mFlags & OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
            delete this;
        }
    }
    refs->decWeak(id);
}

先把強引用減一,判斷是否為最後一個;若是就回呼 onLastStrongRef 通知物件「你可能是最後一個了」,然後檢查生命週期旗標是否為 OBJECT_LIFETIME_STRONG,是則銷毀,否則跳過。再看弱引用:

void RefBase::weakref_type::decWeak(const void* id) {
    weakref_impl* const impl = static_cast<weakref_impl*>(this);
    impl->removeWeakRef(id);
    const int32_t c = android_atomic_dec(&impl->mWeak);
    ALOG_ASSERT(c >= 1, "decWeak called on %p too many times", this);
    if (c != 1) return;

    if ((impl->mFlags & OBJECT_LIFETIME_WEAK) == OBJECT_LIFETIME_STRONG) {
        // 常規生命週期:物件在最後一個強引用消失時銷毀
        if (impl->mStrong == INITIAL_STRONG_VALUE) {
            // 特例:從未有任何強引用,現在才銷毀物件本身
            delete impl->mBase;
        } else {
            delete impl;
        }
    } else {
        // 較少見:生命週期為 OBJECT_LIFETIME_WEAK / FOREVER
        impl->mBase->onLastWeakRef(id);
        if ((impl->mFlags & OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_WEAK) {
            delete impl->mBase;
        }
    }
}

邏輯同樣是先把弱引用減一,不是最後一個就直接返回。若是最後一個,則依生命週期旗標判斷:屬於 OBJECT_LIFETIME_STRONG 時,還要再看強引用是否仍為初始值(也就是根本沒人被強引用過),若是就直接銷毀物件;否則只銷毀計數器 weakref_impl,此時強引用自然歸零,物件的銷毀交由強引用機制完成。若旗標不是 STRONG,則先回呼 onLastWeakRef,再判斷是否為 OBJECT_LIFETIME_WEAK,是則銷毀物件,否則什麼都不做。

這裡有個值得注意的地方:註解提到 OBJECT_LIFETIME_{WEAK|FOREVER},但在我分析的 6.0.1 版本中並沒有 OBJECT_LIFETIME_FOREVER 的定義;而在 2.2.3 版本中確實找得到這個旗標。合理推測是舊版本曾有此定義、新版移除後註解沒有同步更新。這段註解確實容易誤導人。

回到弱指標升級的部分:

if ((impl->mFlags & OBJECT_LIFETIME_WEAK) == OBJECT_LIFETIME_STRONG) {
    // 物件具有"正常"生命週期,最後一個強引用消失時銷毀
    if (curCount <= 0) {
        // 最後一個強引用已釋放,物件無法復活
        decWeak(id);
        return false;
    }
    // 此處 curCount == INITIAL_STRONG_VALUE,從未有人強引用過,可以嘗試提升
    while (curCount > 0) {
        if (android_atomic_cmpxchg(curCount, curCount + 1, &impl->mStrong) == 0) {
            break;
        }
        curCount = impl->mStrong;
    }
    if (curCount <= 0) {
        // 提升失敗,其他執行緒在此期間銷毀了我們
        decWeak(id);
        return false;
    }
}

先判斷是否為 OBJECT_LIFETIME_STRONG:若是,先檢查強引用是否已小於等於 0(全部釋放),是則減弱引用並回傳 false 表示升級失敗;否則把強引用加一。之後又再檢查一次計數——這一步看似多餘,其實是因為物件可能在多執行緒環境中使用,在我們操作的同時可能有另一個執行緒釋放了最後一個強引用,此時物件已被銷毀,必須再確認一次以保證執行緒安全。

若生命週期不是 STRONG(即 OBJECT_LIFETIME_WEAK),則回呼物件的 onIncStrongAttempted 詢問是否允許在此情況下升級。回傳 true 允許,false 拒絕。這個方法可以由目標類自行實作,未實作時使用父類版本:

bool RefBase::onIncStrongAttempted(uint32_t flags, const void* /*id*/) {
    return (flags & FIRST_INC_STRONG) ? true : false;
}

父類的實作很簡單:只要旗標是 FIRST_INC_STRONG(首次強升級)就允許。而我們傳入的正是這個值,所以若目標類沒有覆寫此法,升級永遠會被允許——這一點要特別留意。若不希望此時被升級,就自行實作並回傳 false。允許升級後,把強引用加一。

接著判斷強引用計數是否落在 0 到 INITIAL_STRONG_VALUE 之間(正常範圍)。因為大前提是「從未被強引用過」,所以這裡要回呼 onLastStrongRef 通知物件。最後的收尾程式碼是:

impl->addStrongRef(id);

// 修正計數,且必須在多執行緒下安全
curCount = impl->mStrong;
while (curCount >= INITIAL_STRONG_VALUE) {
    ALOG_ASSERT(curCount > INITIAL_STRONG_VALUE,
            "attemptIncStrong in %p underflowed to INITIAL_STRONG_VALUE", this);
    if (android_atomic_cmpxchg(curCount, curCount - INITIAL_STRONG_VALUE, &impl->mStrong) == 0) {
        break;
    }
    curCount = impl->mStrong;
}
return true;

addStrongRef 在 release 版本中是空實作,僅供除錯使用,這一步實際上會被跳過。之後先取最新的強引用計數,再判斷 mStrong 是否大於 INITIAL_STRONG_VALUE。有人會問:這不是最大值嗎,怎麼可能更大?原因要看 incStrong:

void RefBase::incStrong(const void* id) const {
    weakref_impl* const refs = mRefs;
    refs->incWeak(id);
    refs->addStrongRef(id);
    const int32_t c = android_atomic_inc(&refs->mStrong);
    ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
    if (c != INITIAL_STRONG_VALUE) {
        return;
    }
    android_atomic_add(-INITIAL_STRONG_VALUE, &refs->mStrong);
    refs->mBase->onFirstRef();
}

注意這裡:第一次引用時,先 android_atomic_inc 讓計數變成「初始值 + 1」,此時數值已經大於 INITIAL_STRONG_VALUE,接著才用 android_atomic_add(-INITIAL_STRONG_VALUE, ...) 把初始值減掉,最後才是 1。麻煩的是這兩個操作並非同一個原子動作,中間可能被中斷,因此 attemptIncStrong 最後才需要那段看似奇怪的修正判斷——原始碼註解其實已經說明了這件事。修正完成後回傳 true,代表升級成功。

回到 promote():若 attemptIncStrong 回傳 true,就把 result 這個 sp 的目標指標設為現有物件,讓 sp 能正常操作它;若回傳 false,指標不會被設定,此時操作這個 sp 就會出錯。所以使用前一定要先呼叫 sp 的 get() 確認是否真的升級成功:

inline T* get() const {
    return m_ptr;
}

至此,弱指針的升級流程分析完畢。

sp 與 wp 的示範

最後給一份完整範例,示範 sp、wp 與 RefBase 的搭配使用:

#include <stdio.h>
#include <unistd.h>
#include <utils/RefBase.h>

using namespace android;

class StrongClass : public RefBase {
public:
    StrongClass() {
        printf("create an instance of StrongClass. \n");
    }

    virtual ~StrongClass() {
        printf("destory an instance of StrongClass \n");
    }

    void onFirstRef() {
        printf("StrongClass onFirstRef \n");
    }

    void onLastStrongRef(const void* id) {
        printf("StrongClass onLastStrongRef \n");
    }

    bool onIncStrongAttempted(uint32_t flags, const void* id) {
        printf("StrongClass onIncStrongAttempted \n");
        return true;
    }

    void onLastWeakRef(const void* id) {
        printf("StrongClass onLastWeakRef \n");
    }
};

class WeakClass : public RefBase {
public:
    WeakClass() {
        // 設置生命週期標識位
        extendObjectLifetime(OBJECT_LIFETIME_WEAK);
        printf("create an instance of WeakClass \n");
    }

    virtual ~WeakClass() {
        printf("destory an instance of WeakClass \n");
    }

    void onFirstRef() {
        printf("WeakClass onFirstRef \n");
    }

    void onLastStrongRef(const void* id) {
        printf("WeakClass onLastStrongRef \n");
    }

    bool onIncStrongAttempted(uint32_t flags, const void* id) {
        printf("WeakClass onIncStrongAttempted \n");
        return true;
    }

    void onLastWeakRef(const void* id) {
        printf("WeakClass onLastWeakRef \n");
    }
};

int main(int argc, char** argv) {
    printf("#################### strong class test start #################### \n");

    sp<StrongClass> sp_ptr_1 = new StrongClass();
    sp<StrongClass> sp_ptr_2 = sp_ptr_1;
    wp<StrongClass> wp_ptr_1 = sp_ptr_1;
    wp<StrongClass> wp_ptr_2 = sp_ptr_1;

    printf("1. strong class strong refs: %d \n", sp_ptr_1->getStrongCount());
    printf("2. strong class weak refs: %d \n", wp_ptr_1.get_refs()->getWeakCount());

    sp_ptr_2 = NULL;
    printf("3. strong class strong refs: %d \n", sp_ptr_1->getStrongCount());

    wp_ptr_2 = NULL;
    printf("4. strong class weak refs: %d \n", wp_ptr_1.get_refs()->getWeakCount());
    printf("5. strong class strong refs: %d \n", wp_ptr_1.promote()->getStrongCount());

    printf("6. we are going to release all weak refs!! \n");
    wp_ptr_1 = NULL;

    printf("7. we are going to release all strong refs!! \n");
    sp_ptr_1 = NULL;

    printf("#################### strong class test end #################### \n");
    printf("#################### weak class test start #################### \n");

    sp<WeakClass> sp_ptr_3 = new WeakClass();
    sp<WeakClass> sp_ptr_4 = sp_ptr_3;
    wp<WeakClass> wp_ptr_3 = sp_ptr_3;
    wp<WeakClass> wp_ptr_4 = sp_ptr_3;

    printf("1. weak class strong refs: %d \n", sp_ptr_3->getStrongCount());
    printf("2. weak class weak refs: %d \n", wp_ptr_3.get_refs()->getWeakCount());

    sp_ptr_4 = NULL;
    printf("3. weak class strong refs: %d \n", sp_ptr_3->getStrongCount());

    wp_ptr_4 = NULL;
    printf("4. weak class weak refs: %d \n", wp_ptr_3.get_refs()->getWeakCount());
    printf("5. weak class strong refs: %d \n", wp_ptr_3.promote()->getStrongCount());

    printf("6. we are going to release all strong refs!! \n");
    sp_ptr_3 = NULL;

    printf("7. we are going to release all weak refs!! \n");
    wp_ptr_3 = NULL;

    printf("#################### weak class test end #################### \n");
    return 0;
}

Android.mk:

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE_TAGS := optional
LOCAL_MODULE := strongpointer
LOCAL_SRC_FILES := strongpointer.cpp
LOCAL_SHARED_LIBRARIES := \
    libcutils \
    libutils
include $(BUILD_EXECUTABLE)

執行結果如下:

輸出完全符合預期。特別值得注意的是 WeakClass:透過 extendObjectLifetime(OBJECT_LIFETIME_WEAK) 設定生命週期後,即使所有強引用都已釋放,物件也不會立刻銷毀,要等到最後一個弱引用消失才真正回收。其餘各行輸出為何如此,建議對照前面的講解自行推演一遍,理解會更紮實。

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