深刻淺出,Handler機制外科手術式的剖析(ThreadLocal,Looper,MessageQueen,Message)(上)數據結構
此文是Handler機制的第二篇,第一篇沒有看的小夥伴,能夠戳上邊看一看喲。
上一篇咱們對ThreadLocal和Looper進行了剖析,接着上篇,講講MessageQueen和Handler類。
MessageQueen和Message
MessageQueen是存放Message的,翻譯過來叫消息隊列,可是它內部並非一個消息隊列,而是一個單鏈表的數據結構,裏邊存放的數據就是Message。MessageQueen中的mMseeages字段存放的是頭節點。既然是鏈表,就必定會涉及到插入和取出,咱們先看下它的插入方法:架構
boolean enqueueMessage(Message msg, long when) {
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;
}async
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
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;
}ide
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
這是主要的代碼結構。enqueueMessage的第一個參數是Message,第二個是一個時間戳,他決定了這條Message插入在哪一個節點和何時執行回調。首先會判斷是否正在退出,若是是就不插入消息,直接回收並返回失敗。而後根據when來決定Message插入到哪一個節點,若是頭結點爲null,或者when==0,或者when小於頭結點的when,那麼就把這條數據插入頭結點。else裏邊的邏輯也是相似的,根據兩條數據的when來看看是否該插入這兩條數據中間。最後執行完了返回true,插入成功。函數
取出數據的方法是next,咱們具體看一下:oop
Message next() {
final long ptr = mPtr;
if (ptr == 0) {
return null;
}post
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}ui
nativePollOnce(ptr, nextPollTimeoutMillis);this
synchronized (this) {
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
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 {
nextPollTimeoutMillis = -1;
}
if (mQuitting) {
dispose();
return null;
}spa
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
pendingIdleHandlerCount = 0;
nextPollTimeoutMillis = 0;
}
}
取出數據就伴隨着刪除,它裏邊也是一個無條件的for循環語句。首先從第一個節點去獲取,若是若是沒有數據,就阻塞在那裏,等待native層返回數據,返回數據後就return給looper去處理,退出循環的方式就是根據mQuitting來判斷的,這個字段也是quit方法裏邊改變的。next方法惟一被調用就是在Looper的loop()方法中,能夠結合這剛纔講的loop方法看一下,一目瞭然。下邊附上退出方法的代碼,也就是Looper的quit和quitSafely具體執行的方法:
void quit(boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized (this) {
if (mQuitting) {
return;
}
mQuitting = true;
if (safe) {
removeAllFutureMessagesLocked();
} else {
removeAllMessagesLocked();
}
// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}
MessageQueen小結:MessageQueen中有不少方法涉及到native層,我在這裏沒有剖析,這對於咱們理解MessageQueen的主要邏輯並不會形成影響,有興趣的本身去看看。MessageQueen插入消息依賴的就是時間戳字段when,插入後他全部的消息都是有序的排在其中,取出消息遵循的是從第一個開始獲取,這樣每次都是取頭結點,獲取到以後把頭結點mMessages指向下一個節點,下次再次獲取頭結點,直到所有取出。
Handler
講完了這些以後,咱們來講一下Handler類,這個是整個handler機制暴露給咱們的上層類,發送消息主要是各類send和post,咱們來具體看一下代碼:
public final boolean post(Runnable r){
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
}
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageAtTime(msg, uptimeMillis);
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
從代碼上能夠看出來,全部的返送消息都指向了enqueueMessage(queue, msg, uptimeMillis);這個方法,而這個方法就是在向MessageQueen中插入了一條消息。MessageQueen插入消息以前,有這樣一行代碼:msg.target=this,把handler設置給msg,插入消息以後,MessageQueen的next方法就會返回給looper這條消息,looper收到以後交給Handler處理,主要代碼你點進去能夠看到就是經過msg.target.dispatchMessage(msg);咱們在講looper的時候也說過,這個target就是handler。這裏就再也不贅述,不清楚的哥們本身去看看源碼吧,聯繫起來一目瞭然。
Handler的構造方法有好幾個,意義也不同,咱們單獨講下,咱們最經常使用的是這種構造方法:
public interface Callback {
public boolean handleMessage(Message msg);
}
public Handler() {
this(null, false);
}
public Handler(Callback callback) {
this(callback, false);
}
public Handler(boolean async) {
this(null, async);
}
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
除了 new Handler(),咱們還能夠傳入一個callback來構造Handler,這個callback也有一個handleMessage(msg)方法,這樣就能夠在callback中回調全部的msg。在構造方法中,會去校驗當前線程有沒有looper,沒有的話就會報異常,這也正好解決了咱們在開篇的時候提出的問題。
Handler還有幾個構造方法,能夠傳進去一個Looper:
public Handler(Looper looper) {
this(looper, null, false);
}
public Handler(Looper looper, Callback callback) {
this(looper, callback, false);
}
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
經過傳入Looper在構造Handler的時候,能夠爲Handler指定looper(這不是廢話嗎),有什麼用呢?能夠把Handler的回調切換到咱們建立looper的線程,好比說你在子線程建立的Handler,可是但願灰調函數handleMessage方法執行在主線程,你能夠這也構建:
private Handler mHandler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
// TODO: 9/7/17 do what you wanna
}
};
Handler的這些豐富的構造方法,可以很是便利的幫助咱們切換線程。Handler最後處理Message都是經過dispatchMessage來分發,具體代碼以下所示:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
能夠看出來,message進來以後,並非第一時間交給handleMessage()方法處理的。首先會去看看msg.callback是否爲null,若是非空就執行run方法而後return(這個callback是個Runnable)。這樣的Message須要這樣構建:
Message msg = Message.obtain(mHandler, new Runnable() {
@Override
public void run() {
// TODO: 9/13/17 ....
}
});
而後去看看mCallback是否爲null,mCallback就是咱們在Handler的構造方法時候傳入的:
mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
return false;
}
});
而後根據mCallback.handleMessage方法的返回值來決定是否執行Handler的handleMessage();
這就是dispatchMessage的邏輯,總結下來msg.callback優先級最高,其次Handler.mCallback,最後纔是Handler.handleMessage。
結語:
Handler機制的全部過程到這裏就講完了,若是你跟着博客所有看了一遍,那你確定就理解了他的原理。Handler對於咱們來講,用到的可能只有Handler這一個類,可是它內部的運行思想特別值得咱們借鑑,對於提升咱們的架構能力頗有幫助的。
若是有不許確的地方,歡迎指出。