當在學習跨線程機制 Handler 時,一定會接觸到 Message.obtain() 方法
當在學習Message.obtain 時,可能有幾個疑問:
- Message的集合的具體存儲結構是怎樣的?
- 兩種Message構建方法:Message.obtain() 和 new Message() 之間的區(qū)別?
- Message.obtain() 調用后獲取的鏈表節(jié)點緩存對象會不會形成臟數(shù)據(jù)?
- new Handler().obtainMessage() 和 Message.obtain() 區(qū)別?
弄清這幾個問題的方式還是從源碼入手比較干脆:
問題1:Message的集合的具體存儲結構是怎樣的?
先拋結論:單鏈表(MAX_POOL_SIZE = 50)
- 第1段關鍵代碼位于 Handler.java
在Client調用new Handler().postDelayed()等方法后,沿著調用鏈,會調用到Handler類關鍵方法enqueueMessage(),把Message塞入MessageQueue
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
- 第2段關鍵代碼位于 MessageQueue.java
MessageQueue雖命名為Queue(隊列),但從源碼和Message角度看出,調用MessageQueue postSyncBarrier、enqueueMessage等方法時,邏輯結構是線性表,存儲結構是鏈表而不是隊列;但從注冊的回調監(jiān)聽 - mIdleHandlers看,倒是符合隊列性質;我們姑且叫它為隊列吧
在enqueueMessage中調整消息順序:
新插入消息(節(jié)點=msg)的后繼指針(指針=msg.next)指向當前消息(節(jié)點=mMessages) - msg.next = p;
當前消息指針(指針=mMessages)指向新插入的消息(節(jié)點=msg) - prev.next = msg;
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
問題2:兩種Message構建方法:Message.obtain() 和 new Message() 之間的區(qū)別?
先拋結論:Message.obtain() 比 new Message() 更高效
關鍵代碼:位于 Message.java
調用obtain方法后,優(yōu)先查找Message單鏈表表頭是否已有Message對象,有則利用,無則創(chuàng)建;所以Message.obtain() 和 new Message() 之間的區(qū)別:Message.obtain()更高效,因為節(jié)省了為Message分配、創(chuàng)建、調整內存的操作
/**
* 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();
}
問題3:Message.obtain() 調用后獲取的鏈表節(jié)點緩存對象會不會形成臟數(shù)據(jù)?
先拋結論:不會
關鍵代碼位于:Looper.java
由問題2知,Message.obtain是取緩存操作,Message會持有what、when等變量,如果我們重用表頭的Message,豈不是取到了臟數(shù)據(jù)?
Android SDK當然會解決這個問題:Looper機制,Android的Looper機制原理和設計思想 可類比 iOS中的Runloop,開啟一條線程,同時開啟一個消息循環(huán),制造一個常駐線程
只是Runloop的業(yè)務場景更底層些(內核所啟動的消息循環(huán),控制內核態(tài)和用戶態(tài)切換)
loop()方法實現(xiàn)的最后一行msg.recycleUnchecked()正解決了問題3,每一次loop結尾,Android SDK都會幫我們把執(zhí)行完畢的消息所持有的變量重置到初值,以使下次使用時保證數(shù)據(jù)整潔
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
// Allow overriding a threshold with a system prop. e.g.
// adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
final int thresholdOverride =
SystemProperties.getInt("log.looper."
+ Process.myUid() + "."
+ Thread.currentThread().getName()
+ ".slow", 0);
boolean slowDeliveryDetected = false;
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long traceTag = me.mTraceTag;
long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
if (thresholdOverride > 0) {
slowDispatchThresholdMs = thresholdOverride;
slowDeliveryThresholdMs = thresholdOverride;
}
final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);
final boolean needStartTime = logSlowDelivery || logSlowDispatch;
final boolean needEndTime = logSlowDispatch;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
final long dispatchEnd;
try {
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logSlowDelivery) {
if (slowDeliveryDetected) {
if ((dispatchStart - msg.when) <= 10) {
Slog.w(TAG, "Drained");
slowDeliveryDetected = false;
}
} else {
if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
msg)) {
// Once we write a slow delivery log, suppress until the queue drains.
slowDeliveryDetected = true;
}
}
}
if (logSlowDispatch) {
showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
}
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
msg.recycleUnchecked();
}
}
問題4. new Handler().obtainMessage() 和 Message.obtain() 區(qū)別
先拋結論:沒有區(qū)別
關鍵代碼位于 Handler.java
public final Message obtainMessage()
{
return Message.obtain(this);
}