1關於C++ Layer的記憶體回收機制
Android C++層的記憶體收回主要是通過三個類來實現,分別是RefBase,sp,wp;
SP和WP是兩個智能指標模板類,sp是strong pointer,wp則是weak pointer,亦我們常說的強引用和弱引用;執行個體化sp和wp這兩個模板類的類型必須是派生自RefBase的類
1.1 RefBase類
因為這個類擁有對記憶體回收機制的預設實現,所以android上想要支援記憶體回收機制的類必須派生自RefBase
下面簡單介紹下成員變數和成員函數:
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,
它主要包含了對弱引用計數的基本操作,
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也是永遠都會成功的
在增加或者減少強引用計數的同時,弱引用計數也會被增加或減少,它們總是配對出現的,下面簡單看下幾個關鍵區段的代碼:
//增加強引用計數
void RefBase::incStrong(const void* id) const
{
weakref_impl* const refs = mRefs;
//store the object which makes strong reference up, just for track & debug, it is an empty //function
refs->addWeakRef(id);
//increment weak reference
refs->incWeak(id);
//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.
refs->addStrongRef(id);
const int32_t c = android_atomic_inc(&refs->mStrong);
LOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
#if PRINT_REFS
LOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
#endif
if (c != INITIAL_STRONG_VALUE) {
return;
}
//if the previous value of mStrong equals INITIAL_STRONG_VALUE
//first for increment strong reference
android_atomic_add(-INITIAL_STRONG_VALUE, &refs->mStrong);
//notify first reference done
const_cast<RefBase*>(this)->onFirstRef();
}
//增加弱引用計數
void RefBase::weakref_type::incWeak(const void* id)
{
weakref_impl* const impl = static_cast<weakref_impl*>(this);
//如上面所寫,儲存id只為做debug用
impl->addWeakRef(id);
const int32_t c = android_atomic_inc(&impl->mWeak);
LOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
}
接下是兩個減少引用計數的函數,因為這兩個函數涉及到對象的銷毀,所以講的詳細點
//減少強引用計數
void RefBase::decStrong(const void* id) const
{
weakref_impl* const refs = mRefs;
refs->removeStrongRef(id);
const int32_t c = android_atomic_dec(&refs->mStrong);
#if PRINT_REFS
LOGD("decStrong of %p from %p: cnt=%d\n", this, id, c);
#endif
LOG_ASSERT(c >= 1, "decStrong() called on %p too many times", refs);
//強引用減完後為零,嘗試銷毀對象
if (c == 1) {
const_cast<RefBase*>(this)->onLastStrongRef(id);
//如果未標明OBJECT_LIFETIME_WEAK,也就是預設的life time,銷毀對象
if ((refs->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK) {
delete this;
}
}
refs->removeWeakRef(id);
refs->decWeak(id);
}
//減少弱引用計數
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);
LOG_ASSERT(c >= 1, "decWeak called on %p too many times", this);
if (c != 1) return;
//c == 1,弱引用為0,開嘗試釋放對象
if ((impl->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK) {
//預設life time ,並且對象強引用計數為預設初始值(無強引用計數),釋放對象
if (impl->mStrong == INITIAL_STRONG_VALUE)
delete impl->mBase;
else {
//LOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase) ;
//反之釋放內部引用管理類
delete impl;
}
} else {
//OBJECT_LIFETIME_WEAK,並且life time不包含OBJECT_LIFETIME_FOREVER,釋放對象
impl->mBase->onLastWeakRef(id);
if ((impl->mFlags&OBJECT_LIFETIME_FOREVER) != OBJECT_LIFETIME_FOREVER) {
delete impl->mBase;
}
}
}
如果對上面一會釋放imple->mBase,一會釋放weakref_impl有疑問,繼續看RefBase的解構函式:
RefBase::~RefBase()
{
if (mRefs->mWeak == 0) {
delete mRefs;
}
}
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做了哪些操作:
template<typename T>
sp<T> wp<T>::promote() const
{
//使用wp內的raw pointer和引用管理類來建立sp
return sp<T>(m_ptr, m_refs);
}
template<typename T>
sp<T>::sp(T* p, weakref_type* refs)
: m_ptr((p && refs->attemptIncStrong(this)) ? p : 0)
{
}
調用引用管理類的函數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的強引用和弱引用類似,下面用代碼來粗略的描述下sp和wp的使用:
class A : public RefBase{
//…
}
sp<A> sp_inst(new A());
wp<A> wp_weak(sp_inst);
然後wp在使用前,需要
sp<A> sp_promote = wp.promote();
//promote 失敗
If (sp_promote == NULL)
{
//重新建立對象
sp<A> sp_new(new A());
sp_promote = sp_new;
}