引言
Android中乞而,我們在線程之間通信傳遞通常采用Android的消息機(jī)制送悔,而這機(jī)制傳遞的正是Message。
通常爪模,我們使用Message.obtain()和Handler.obtainMessage()從Message Pool中獲取Message欠啤,避免直接構(gòu)造Message。
- 那么Android會否因為Message Pool緩存的Message對象而造成OOM呢屋灌?
對于這個問題洁段,我可以明確的說APP不會因Message Pool而OOM。至于為什么共郭,可以一步步往下看祠丝,心急的可以直接看最后一節(jié)——Message Pool如何存放Message。
Obtain分析
/**
* Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
* creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
* If you don't want that facility, just call Message.obtain() instead.
*/
public final Message obtainMessage()
{
return Message.obtain(this);
}
顯然除嘹,Handler.obtain()是調(diào)用Message.obtain()來獲取的写半。那么我門再來看下Message.obtain()源碼
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
*/
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
上述代碼給我們透露幾個個關(guān)鍵信息:
- 學(xué)過一點數(shù)據(jù)結(jié)構(gòu)的,從上面的代碼片基本就能推斷出sPool是一個鏈表結(jié)構(gòu)尉咕,另外sPool本身就是Message叠蝇。
- 若鏈表sPool不為空,那么obtain()方法會從鏈表sPool頭部取出一個Message對象賦值給m年缎,并作為返回值返回悔捶;否則铃慷,直接new一個Message對象。
劇透下這里的sPool其實就是Message Pool
Message Pool相關(guān)源碼分析
Message Pool數(shù)據(jù)結(jié)構(gòu)
public final class Message implements Parcelable {
// sometimes we store linked lists of these things
/*package*/ Message next;
private static final Object sPoolSync = new Object();
private static Message sPool;
private static int sPoolSize = 0;
private static final int MAX_POOL_SIZE = 50;
}
看到關(guān)鍵信息了沒炎功?Message的成員有next枚冗、sPool和sPoolSize缓溅,這對于稍微學(xué)過一點數(shù)據(jù)結(jié)構(gòu)的蛇损,很快就能推斷出這是一個典型的鏈表結(jié)構(gòu)的實現(xiàn)。sPool就是一個全局的消息池即鏈表坛怪,next記錄鏈表中的下一個元素淤齐,sPoolSize記錄鏈表長度,MAX_POOL_SIZE表示鏈表的最大長度為50袜匿。
Message Pool如何存放Message
public final class Message implements Parcelable {
private static boolean gCheckRecycle = true;
/** @hide */
public static void updateCheckRecycle(int targetSdkVersion) {
if (targetSdkVersion < Build.VERSION_CODES.LOLLIPOP) {
gCheckRecycle = false;
}
}
/**
* Return a Message instance to the global pool.
* <p>
* You MUST NOT touch the Message after calling this function because it has
* effectively been freed. It is an error to recycle a message that is currently
* enqueued or that is in the process of being delivered to a Handler.
* </p>
*/
public void recycle() {
if (isInUse()) {
if (gCheckRecycle) {
throw new IllegalStateException("This message cannot be recycled because it "
+ "is still in use.");
}
return;
}
recycleUnchecked();
}
/**
* Recycles a Message that may be in-use.
* Used internally by the MessageQueue and Looper when disposing of queued Messages.
*/
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = -1;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
}
從代碼分析上看更啄,消息池存放的核心方法就是上面的recycleUnchecked()方法:
- 將待回收的Message對象字段置空(避免因Message過大,使靜態(tài)的消息池內(nèi)存泄漏)居灯。因此無論原先的Message對象有多大祭务,最終被緩存進(jìn)Message Pool前都被置空,那么這些緩存的Message對象所占內(nèi)存大小對于一個app內(nèi)存來說基本可以忽略怪嫌。所以說义锥,Message Pool并不會造成App的OOM。
- 以內(nèi)置鎖的方式(線程安全)岩灭,判斷當(dāng)前線程池的大小是否小于50拌倍。若小于50,直接將Mesaage插入到消息池鏈表尾部噪径;若大于等于50柱恤,則直接丟棄掉,那么這些被丟棄的Message將交由GC處理找爱。
總結(jié)
- 從數(shù)據(jù)結(jié)構(gòu)的角度上說梗顺,Message Pool是一個鏈表,她是Message中的靜態(tài)成員sPool车摄;從類型定義上說寺谤,Message Pool的類型就是Message,因為sPool的類型定義是Message练般。
- Message Pool不會因為緩存Message對象而造成OOM矗漾。