Handler、Looper、MessageQueue源碼解析——MessageQueue



MessageQueue


/**
* Low-level class holding the list of messages to be dispatched by a
* {@link Looper}. Messages are not added directly to a MessageQueue,
* but rather through {@link Handler} objects associated with the Looper.
* You can retrieve the MessageQueue for the current thread with
* {@link Looper#myQueue() Looper.myQueue()}.
*/

Handler時用來發(fā)送消息的,調(diào)用sendMessageAtTime(),在調(diào)用MessageQueue的enqueueMessage(msg, uptimeMillis)方法,把消息插入到MessageQueue中。我們首先來看一下MessageQueue的enqueueMessage方法:

    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;
    }```

在Looper的loop()方法中,開啟了一個死循環(huán),通過調(diào)用MessageQueue的next()方法,不斷的取出消息,再交給Handler去處理。

Message msg = queue.next();```

我們來看一下MessageQueue的next()方法:

    Message next() {
        //注釋1
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                //注釋2
                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());
                }
                //注釋3
                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;
                }

                // Process the quit message now that all pending messages have been handled.
                //注釋4
                if (mQuitting) {
                    dispose();
                    return null;
                }

    }```

首先看注釋1:mPrt==0時返回一個null,mPrt在什么時候為空呢,注意到有一個dispose()方法:

private void dispose() {
    if (mPtr != 0) {
        nativeDestroy(mPtr);
        mPtr = 0;
    }
}```

dispose()方法在哪調(diào)用呢,注意到在注釋4處,當(dāng)mQuitting==true時調(diào)用dispose()方法。那么mQuitting在哪賦值為true呢:

    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);
        }
    }```

也就是上節(jié)我們說到調(diào)用Looper中的quit()獲得quitSafely()時會賦值為true,MessageQueue退出循環(huán)。

再看注釋3:Message是一個單向鏈表,next指向下一個Message。首先會先判斷當(dāng)前時間與Message的時間對比:

//獲取從開機(jī)到現(xiàn)在的時間
final long now = SystemClock.uptimeMillis();

when = SystemClock.uptimeMillis()+uptimeMillis;```

如果message已經(jīng)準(zhǔn)備好,則返回一個Message對象,并把Message的next指針指向下一個message。

再看注釋2:什么時候message的target對象為空,在Handler發(fā)送Message時制定了target對象,當(dāng)message的target對象為空時說明不是由Handler插入進(jìn)來的,在MessageQueue的源碼中找到這樣一個方法;

    private int postSyncBarrier(long when) {
        // Enqueue a new sync barrier token.
        // We don't need to wake the queue because the purpose of a barrier is to stall it.
        synchronized (this) {
            final int token = mNextBarrierToken++;
            final Message msg = Message.obtain();
            msg.markInUse();
            msg.when = when;
            msg.arg1 = token;

            Message prev = null;
            Message p = mMessages;
            if (when != 0) {
                while (p != null && p.when <= when) {
                    prev = p;
                    p = p.next;
                }
            }
            if (prev != null) { // invariant: p == prev.next
                msg.next = p;
                prev.next = msg;
            } else {
                msg.next = p;
                mMessages = msg;
            }
            return token;
        }
    }```
相當(dāng)于設(shè)置一個消息屏障,如果遇到一個消息屏障,就會不停的循環(huán)找到一個異步消息,一般我們使用的都是同步消息,我們可以通過Message的setAsynchronous(true)方法指定為異步消息。

既然有開始循環(huán),那么必定會有退出循環(huán),我們調(diào)用Looper的quit()或者quitSafely()方法時實際調(diào)用的是MessageQueue的quit方法。quit()和quitSafely()方法的區(qū)別在Looper中已經(jīng)提到了,分別調(diào)用了
removeAllMessagesLocked()和removeAllFutureMessagesLocked()方法,現(xiàn)在我們來看一下具體實現(xiàn):

private void removeAllMessagesLocked() {
    Message p = mMessages;
    while (p != null) {
        Message n = p.next;
        p.recycleUnchecked();
        p = n;
    }
    mMessages = null;
}```

因為Message是一個單向鏈表,把所有的Message回收掉。

   private void removeAllFutureMessagesLocked() {
       final long now = SystemClock.uptimeMillis();
       Message p = mMessages;
       if (p != null) {
           if (p.when > now) {
               removeAllMessagesLocked();
           } else {
               Message n;
               for (;;) {
                   n = p.next;
                   if (n == null) {
                       return;
                   }
                   if (n.when > now) {
                       break;
                   }
                   p = n;
               }
               p.next = null;
               do {
                   p = n;
                   n = p.next;
                   p.recycleUnchecked();
               } while (n != null);
           }
       }
   }```

當(dāng)p.when > now時,即又延時的消息全部清空,對于沒有延時的消息,通過一個死循環(huán)等待Handler處理完再回收。

我們注意到無論是Looper的loop()方法還是MessageQueue的next()方法,都是一個死循環(huán),那么為什么不會造成阻塞或者對CPU有什么消耗上的影響?請參考知乎大神回答:[Android中為什么主線程不會因為Looper.loop()里的死循環(huán)卡死?](https://www.zhihu.com/question/34652589)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容