調(diào)用Looper.quit()和Looper.quitsafely()的時(shí)候發(fā)生了什么花沉?
根據(jù)官方文檔:
Looper.quit()
調(diào)用后直接終止
Looper
,不在處理任何Message
拴念,所有嘗試把Message
放進(jìn)消息隊(duì)列的操作都會(huì)失敗垛孔,比如Handler.sendMessage()
會(huì)返回 false豆同,但是存在不安全性橘蜜,因?yàn)橛锌赡苡?code>Message還在消息隊(duì)列中沒來的及處理就終止Looper
了。
Looper.quitsafely()
調(diào)用后會(huì)在所有消息都處理后再終止
Looper
垄分,所有嘗試把Message
放進(jìn)消息隊(duì)列的操作也都會(huì)失敗搓译。
Looper
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
...
for (;;) {
// 獲取消息隊(duì)列中的下一個(gè)消息,如果消息隊(duì)列沒有消息就阻塞
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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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);
}
// 最后回收這個(gè) Message
msg.recycleUnchecked();
}
}
/**
* Quits the looper.
* <p>
* Causes the {@link #loop} method to terminate without processing any
* more messages in the message queue.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p><p class="note">
* Using this method may be unsafe because some messages may not be delivered
* before the looper terminates. Consider using {@link #quitSafely} instead to ensure
* that all pending work is completed in an orderly manner.
* </p>
*
* @see #quitSafely
*/
public void quit() {
mQueue.quit(false);
}
/**
* Quits the looper safely.
* <p>
* Causes the {@link #loop} method to terminate as soon as all remaining messages
* in the message queue that are already due to be delivered have been handled.
* However pending delayed messages with due times in the future will not be
* delivered before the loop terminates.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p>
*/
public void quitSafely() {
mQueue.quit(true);
}
都調(diào)用了MessageQueue
的quit(boolean)
MessageQueue
Message next() {
...
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
if (mQuitting) {
dispose();
return null;
}
...
}
...
}
void quit(boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized (this) {
if (mQuitting) {
return;
}
mQuitting = true; // 先把 mQuitting 改為 true
if (safe) {
removeAllFutureMessagesLocked();
} else {
removeAllMessagesLocked();
}
// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}
private void removeAllMessagesLocked() {
Message p = mMessages; // mMessages 是消息隊(duì)列單鏈表的表頭
// 消息隊(duì)列所有消息都執(zhí)行 recycleUnchecked() 進(jìn)行回收
while (p != null) {
Message n = p.next;
p.recycleUnchecked();
p = n;
}
// 最后把 mMessages 設(shè)置為 null Looper 的 for 循環(huán)就會(huì)結(jié)束
mMessages = null;
}
private void removeAllFutureMessagesLocked() {
final long now = SystemClock.uptimeMillis();
Message p = mMessages;
if (p != null) {
//如果表頭的消息是延遲消息锋喜,那么整個(gè)消息隊(duì)列都可以直接回收了
if (p.when > now) {
removeAllMessagesLocked();
} else {
Message n;
for (;;) {
n = p.next;
if (n == null) {
return;
}
// 如果當(dāng)前消息是延遲消息,跳出循環(huán)剩下消息進(jìn)入 do while 循環(huán)
if (n.when > now) {
break;
}
p = n;
}
p.next = null;
do {
p = n;
n = p.next;
p.recycleUnchecked();
} while (n != null);
}
}
}
在這里我們先回顧一下Message
是怎么在Looper
豌鸡、MessageQueue
和Handler
中傳遞了嘿般,我們知道當(dāng)Looper.loop()
被執(zhí)行后Handler機(jī)制
就啟動(dòng)了,根據(jù)上面的代碼可以看到loop()
里面有一個(gè)for循環(huán)涯冠,只有當(dāng)MessageQueue
的next()
返回null
的時(shí)候才會(huì)退出循環(huán)終止Handler機(jī)制
炉奴。再看看MessageQueue
的next()
我們也看到一個(gè)for循環(huán),如果有消息的話就把消息返回蛇更,沒有消息且mQuitting=false
的時(shí)候繼續(xù)循環(huán)下去瞻赶,只有當(dāng)沒有消息然后mQuitting=true
的時(shí)候返回null
。
根據(jù)Looper
代碼所示Looper.quit()
最終會(huì)調(diào)用MessageQueue.removeAllMessagesLocked()
派任,而Looper.quitsafely()
會(huì)調(diào)用MessageQueue.removeAllFutureMessagesLocked()
砸逊。
- removeAllMessagesLocked() 表示直接把消息隊(duì)列里面的消息清空
- removeAllFutureMessagesLocked() 表示把所有延遲消息清除
根據(jù)我在上面代碼中寫的注釋我們可以總結(jié)Looper.quit()
和Looper.quitsafely()
做了什么和區(qū)別在哪里。
quit()實(shí)際上是把消息隊(duì)列全部清空掌逛,然后讓MessageQueue.next()返回null令Looper.loop()循環(huán)結(jié)束從而終止Handler機(jī)制
师逸,但是存在著不安全的地方是可能有些消息在消息隊(duì)列沒來得及處理。而quitsafely()
做了優(yōu)化豆混,只清除消息隊(duì)列中延遲信息篓像,等待消息隊(duì)列剩余信息處理完之后再終止Looper
循環(huán)。
所有Message
被回收都需要調(diào)用Message.recycleUnchecked()
皿伺,那么Message
的回收機(jī)制是怎樣的呢员辩,可以看看下面的代碼和注釋:
Message
/**
* 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
Message m = sPool;
sPool = m.next;
m.next = null;
// 在這里把 recycleUnchecked() 中回收時(shí)設(shè)置的 in-use 標(biāo)志去掉
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
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
過程分為兩步:
1 先把Message
的變量初始化并標(biāo)記為 in-use
令該Message
無法被發(fā)送到消息隊(duì)列。
2 判斷Message緩存池
緩存數(shù)量是否達(dá)到上限(默認(rèn)50)鸵鸥,Message緩存池
也是一個(gè)鏈表奠滑,沒有的話就通過把Message
以頭部添加方式放到緩存池中。
Message
提供一個(gè)obtain()
方法從緩存池中獲取回收的Message
官方推薦需要?jiǎng)?chuàng)建
Message
對(duì)象的時(shí)候通過Message.obtain()
來獲取。