Android C++层的内存回收机制

1关于C++ Layer的内存回收机制

Android C++层的内存收回主要是通过三个类来实现,分别是RefBase,sp,wp;

SP和WP是两个智能指针模板类,sp是strong pointer,wp则是weak pointer,亦我们常说的强引用和弱引用;实例化sp和wp这两个模板类的类型必须是派生自RefBase的类

1.1  RefBase类

因为这个类拥有对内存回收机制的默认实现,所以android上想要支持内存回收机制的类必须派生自RefBase

Android C++层的内存回收机制_第1张图片

下面简单介绍下成员变量和成员函数:

mRefs:

weakref_impl对象,派生于RefBase::weakref_type, 包含了对strong ref和weak ref的具体实现,也就是说RefBase中只包含了一些对外的标准操作,具体的实现在weakref_impl内

void incStrong(const void *id):

强引用计数加1,参数id主要用在debug时跟踪调试,一般都为sp或者wp的对象指针

void decStrong(const void *id):

强引用计数减1,参数id含义同上

void forceIncStrong(const void *id):

强制引用计数加1

Int32_t getStrongCount():

获去强引用计数值

weakref_type * createWeak(const void *id)

弱引用计数加1,然后返回weakref_impl对象

weakref_type* getWeakRefs()

获取weakref_impl对象

void extendObjectLifetime(int32_t mode):

扩展对象的生命期,默认为0,可设置为

OBJECT_LIFETIME_WEAK   = 0x0001,

OBJECT_LIFETIME_FOREVER = 0x0003

这几个参数的作用在下面会详细描述

virtual void onFirstRef()

虚函数,在第一次新增引用计数时,会调用此函数,接下去的其他函数都类似

 

上面也有提到了,RefBase有一个内部基类weakref_type,

Android C++层的内存回收机制_第2张图片

它主要包含了对弱引用计数的基本操作,

void incWeak(const void*id):

弱引用计数加1,id参数的意义同上

void decWeak(const void *id):

弱引用计数减1,id同上

bool attemptIncStrong(const void *id):

尝试增加强引用计数,这个函数会在wp promote获取sp时被调用,主要确认wp promote为sp是否成功

bool attemptIncWeak(const void *id):

尝试增加弱引用计数,这个功能只在object lifetime设置为OBJECT_LIFETIME_FOREVER有效

Int32_t getWeakCount():

获取弱引用计数值

 

在RefBase中,可以通过extendObjectLifetime来设置lifetime,有三种life time:

1:default(0),强引用和弱引用的默认行为,不管弱应用计数的值为多少,只要强引用计数的值为0,就释放对象

2:OBJECT_LIFETIME_WEAK,在这种状态下,如果强引用为0时,对象不会被释放,只有在弱引用计数为0的情况下,对象才会被释放

3:OBJECT_LIFETIME_WEAK | OBJECT_LIFETIME_FOREVER,在这种状态下,对象永不会释放

 

第三种情况比较猛,设置了,除非主动delete raw pointer,否则在sp和wp的规则下,是不会被释放的,当然,promote也是永远都会成功的

 

在增加或者减少强引用计数的同时,弱引用计数也会被增加或减少,它们总是配对出现的,下面简单看下几个关键部分的代码:

//增加强引用计数

查看源码 打印 ?
01 void RefBase::incStrong(const void* id) const
02  
03 {
04  
05 weakref_impl* const refs = mRefs;
06  
07 //store the object which makes strong reference up, just for track & debug, it is an empty //function
08  
09 refs->addWeakRef(id);
10  
11 //increment weak reference
12  
13     refs->incWeak(id);
14  
15 //store the object which makes strong reference up, just for track & debug, if not in debug, it //is an empty function, nothing will be done.
16  
17     refs->addStrongRef(id);
18  
19     const int32_t c = android_atomic_inc(&refs->mStrong);
20  
21     LOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
22  
23 #if PRINT_REFS
24  
25     LOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
26  
27 #endif
28  
29     if (c != INITIAL_STRONG_VALUE)  {
30  
31         return;
32  
33 }
34  
35   
36  
37 //if the previous value of mStrong equals INITIAL_STRONG_VALUE
38  
39 //first for increment strong reference
40  
41 android_atomic_add(-INITIAL_STRONG_VALUE, &refs->mStrong);
42  
43 //notify first reference done
44  
45     const_cast<RefBase*>(this)->onFirstRef();
46  
47 }

 

//增加弱引用计数

查看源码 打印 ?
01 void RefBase::weakref_type::incWeak(const void* id)
02  
03 {
04  
05 weakref_impl* const impl = static_cast<weakref_impl*>(this);
06  
07 //如上面所写,保存id只为做debug用
08  
09     impl->addWeakRef(id);
10  
11     const int32_t c = android_atomic_inc(&impl->mWeak);
12  
13     LOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
14  
15 }

 

接下是两个减少引用计数的函数,因为这两个函数涉及到对象的销毁,所以讲的详细点

//减少强引用计数

查看源码 打印 ?
01 void RefBase::decStrong(const void* id) const
02  
03 {
04  
05     weakref_impl* const refs = mRefs;
06  
07     refs->removeStrongRef(id);
08  
09     const int32_t c = android_atomic_dec(&refs->mStrong);
10  
11 #if PRINT_REFS
12  
13     LOGD("decStrong of %p from %p: cnt=%d\n", this, id, c);
14  
15 #endif
16  
17 LOG_ASSERT(c >= 1, "decStrong() called on %p too many times", refs);
18  
19 //强引用减完后为零,尝试销毁对象
20  
21     if (c == 1) {
22  
23         const_cast<RefBase*>(this)->onLastStrongRef(id);
24  
25         //如果未标明OBJECT_LIFETIME_WEAK,也就是默认的life time,销毁对象
26  
27         if ((refs->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK) {
28  
29             delete this;
30  
31         }
32  
33     }
34  
35     refs->removeWeakRef(id);
36  
37     refs->decWeak(id);
38  
39 }

 

//减少弱引用计数

查看源码 打印 ?
01 void RefBase::weakref_type::decWeak(const void* id)
02  
03 {
04  
05     weakref_impl* const impl = static_cast<weakref_impl*>(this);
06  
07     impl->removeWeakRef(id);
08  
09     const int32_t c = android_atomic_dec(&impl->mWeak);
10  
11     LOG_ASSERT(c >= 1, "decWeak called on %p too many times", this);
12  
13     if (c != 1) return;
14  
15     //c == 1,弱引用为0,开尝试释放对象
16  
17 if ((impl->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK) {
18  
19     //默认life time ,并且对象强引用计数为默认初始值(无强引用计数),释放对象
20  
21         if (impl->mStrong == INITIAL_STRONG_VALUE)
22  
23             delete impl->mBase;
24  
25         else {
26  
27 //LOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase) ;
28  
29     //反之释放内部引用管理类
30  
31             delete impl;
32  
33         }
34  
35 } else {
36  
37   //OBJECT_LIFETIME_WEAK,并且life time不包含OBJECT_LIFETIME_FOREVER,释放对象
38  
39         impl->mBase->onLastWeakRef(id);
40  
41         if ((impl->mFlags&OBJECT_LIFETIME_FOREVER) != OBJECT_LIFETIME_FOREVER) {
42  
43             delete impl->mBase;
44  
45         }
46  
47     }
48  
49 }

 

如果对上面一会释放imple->mBase,一会释放weakref_impl有疑问,继续看RefBase的析构函数:

查看源码 打印 ?
01 RefBase::~RefBase()
02  
03 {
04  
05     if (mRefs->mWeak == 0) {
06  
07         delete mRefs;
08  
09     }
10  
11 }

RefBase被销毁时,只有当弱引用计数为0时,才会释放weakref_imp对象,上面decWeak中第一和第三个delete,直接释放impl->mBase,肯定没问题,因为这时候弱引用计数已经为0,weakref_imp对象在析构中正常被释放

 

再看第二个delete,在默认life time下,如果RefBase通过sp建立了强引用,在强引用为0的情况下在执行RefBase::decStrong中的以下代码,

if ((refs->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK) {

     delete this;

}

RefBase对象肯定会被释放,在释放时调用析构时,由于mRefs->mWeak == 0不成立,内部weaktype_imp对象不会被释放,所以这里需要delete impl以释放内部引用管理对象

1.2  创建sp和wp对象

创建sp:

    sp(T* other):直接使用Raw pointer来创建sp对象

sp(const sp<T>& other):从已有的sp对象拷贝构造

创建wp:

    wp(T* other):直接使用raw pointer来创建wp对象

    wp(const wp<T>& other):从已有的wp对象拷贝

wp(const sp<T>& other):从已有的sp对象拷贝

1.3  关于promote

如果想通过已有的wp对象获取对应的内建对象,需要调用promote来尝试提升为sp,然后通过sp来判断promote是否成功,如果成功,说明内建对象还存在,可以继续使用,反之,需要创建新的内建对象

 

下面来详细查看下promote做了哪些操作:

查看源码 打印 ?
01 template<typename T>
02  
03 sp<T> wp<T>::promote() const
04  
05 {
06  
07     //使用wp内的raw pointer和引用管理类来创建sp
08  
09     return sp<T>(m_ptr, m_refs);
10  
11 }
12  
13   
14  
15 template<typename T>
16  
17 sp<T>::sp(T* p, weakref_type* refs)
18  
19     : m_ptr((p && refs->attemptIncStrong(this)) ? p : 0)
20  
21 {
22  
23 }

调用引用管理类的函数attemptIncStrong来尝试增加强引用计数,如成功,说明raw pointer保存的对象还未被释放,可以继续使用,反之,返回false,promote失败

接下去详细看下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;

    LOG_ASSERT(curCount >= 0, "attemptIncStrong called on %p after underflow",

               this);

    //如果强引用计数不为初始值并且大于0,说明对象还活着,赶紧将引用计数+1

    while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {

        if (android_atomic_cmpxchg(curCount, curCount+1, &impl->mStrong) == 0) {

            break;

        }

        curCount = impl->mStrong;

    }

//如果强引用计数<=0或者初始值,就代表对象已经被释放了吗?

//不一定

    if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {

        bool allow;

        if (curCount == INITIAL_STRONG_VALUE) {

            // attempting to acquire first strong reference...  this is allowed

            // if the object does NOT have a longer lifetime (meaning the

            // implementation doesn't need to see this), or if the implementation

            // allows it to happen.

            /*curCount为初始值,说明sp未被创建,从一开始都是wp独自掌管,这种情况下,对象肯定存在,剩下就是根据程序需要,让不让它promote成功

            根据以下代码,有两种情况:

            1:生命期不为OBJECT_LIFETIME_WEAK,这时第一判断为true,onIncStrongAttempted结果忽略,allow为true

            2:生命期为OBJECT_LIFETIME_WEAK时,这时就要看onIncStrongAttempted的结果了,默认该函数返回都为true,也就是说,程序的默认行为,allow都为true;当然你也可以在自己的类中

根据需要修改onIncStrongAttempted的默认行为来控制是否允许在这种情况下让其promote成功*/

            allow = (impl->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK

                  || impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id);

        } else {

            // Attempting to revive the object...  this is allowed

            // if the object DOES have a longer lifetime (so we can safely

            // call the object with only a weak ref) and the implementation

            allow = (impl->mFlags&OBJECT_LIFETIME_WEAK) == OBJECT_LIFETIME_WEAK

                  && impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id);

        }

        //不允许, promote失败

        if (!allow) {

            decWeak(id);

            return false;

        }

        curCount = android_atomic_inc(&impl->mStrong);

 

        // If the strong reference count has already been incremented by

        // someone else, the implementor of onIncStrongAttempted() is holding

        // an unneeded reference.  So call onLastStrongRef() here to remove it.

        // (No, this is not pretty.)  Note that we MUST NOT do this if we

        // are in fact acquiring the first reference.

        if (curCount > 0 && curCount < INITIAL_STRONG_VALUE) {

            impl->mBase->onLastStrongRef(id);

        }

    }

   

    impl->addWeakRef(id);

    impl->addStrongRef(id);

 

#if PRINT_REFS

    LOGD("attemptIncStrong of %p from %p: cnt=%d\n", this, id, curCount);

#endif

 

    if (curCount == INITIAL_STRONG_VALUE) {

        android_atomic_add(-INITIAL_STRONG_VALUE, &impl->mStrong);

        impl->mBase->onFirstRef();

    }

   

    return true;

}

 

attemptIncStrong成功,promote成功,继续使用已有的Refbase对象实例,如果失败了,则需重新创建新的对象。

 

1.4  用处

在android中,在实现基于RefBase的类中,大部分都使用默认的生命期,只有BpBinder会调用 extendObjectLifetime(OBJECT_LIFETIME_WEAK)来更改默认生命期;针对默认生命期,其用处和java的强引用和 弱引用类似。


你可能感兴趣的:(Android C++层的内存回收机制)