MessageQuene
MessageQuene在Android中是消息队列的意思,但内部存储结构并不是队列,而是采用单向链表的数据结构形式存储消息。是Handler的具体实现之一(另外一个是Looper)。
MessageQuene#enqueueMessage()
enqueueMessage()是MessageQuene消息插入的实现方法,其实就是一个链表的插入操作。
boolean enqueueMessage(Message msg, long when) {
// 如果该消息没有目标handler
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;
// 如果还有没消息进入或者延迟时间为0或者延迟时间小于上一个消息的延迟时间,则进入if判断中
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;
}
1、当第一个消息msg1插入时,因为mMessages为null,所以p也为null,接下来会进入到if判断里面。
2、当第二个消息msg2插入时,假设msg2的延迟时间为0或者小于头结点的延迟时间(即when = 0 || when < p.when)。
3、当后续消息插入时,假设延时时间不为0并且延时时间不小于头结点的延时时间(即不满足when = 0 || when < p.when),则会进入到else判断中执行下面这段代码。
for (;;) {
// 上一个节点
prev = p;
// 下一个节点(即上一个节点的后面一个节点)
p = p.next;
// 表示已经遍历完成或者当前被插入的消息的延迟时间小于当前被遍历到的消息的延迟时间
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
// 把msg插入prev节点和p节点之间
msg.next = p; // invariant: p == prev.next
prev.next = msg;
首先会进入无限循环,结束循环的条件是p == null || when < p.when(即已经遍历到消息链表的最后一个节点或者当前被插入的消息的延迟时间小于当前被遍历到的消息的延迟时间)。结束循环后会把msg插入prev节点和p节点之间。
总结
由上面分析可以看出mMessages始终充当的是消息链表的头结点。当没有消息或者消息延时时间为0或者消息的延时时间比头结点的延时时间短时都采用的是链表头插的方式。其他时候是通过比较延迟时间,按照延迟时间长短顺序插入(延迟时间越短越靠前,会被优先处理)。
MessageQuene#next()
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
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;
// 消息不为空并且没有目标Handler
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;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
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);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
next()方法比较简单,就是从头结点开始,无限循环消息链表,一直取消息,有消息便会返回这条消息交给Looper处理并从消息链表中移除这条消息,没有就会一直阻塞在这里。因为一般情况下msg.target不为null(即目标Handler不为null),所以会进入到if (msg != null)判断中。并且执行下面的程序:
// 由上面代码得知prevMsg = null
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
// 因为mMessages始终是头结点,把mMessages指向头结点的下一个节点,
// 就相当于移除了头结点(即是移除了将被返回的消息)
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
// 标记正在使用
msg.markInUse();
// 返回msg
return msg;
因为消息是按照执行的先后顺序插入的(优化被执行的排在前面),所以取消息的从头结点开始取。