Handler 机制的核心要点
- 延时消息是怎么处理的
- 如何处理消息队列为空的情况。
- native,java两个世界的消息通信的区别和联系
- 主线程的Loop在哪启动
- handler内存泄漏的原理
后续针对每个问题详细分析。只了解handler,loop,messageque是干嘛的,这是不够的。
延时消息怎么处理的
- 以postDelay为起点
public final boolean postDelayed(Runnable r, long delayMillis)
{
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
//说明该消息理论上在delayMillis 加上系统的当前时间之后执行
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
- 省略中间的调用链,最终调用MessageQueue.enqueueMessage,省略无关代码。两个步骤,先赋值when变量,找到合适的节点插入。
boolean enqueueMessage(Message msg, long when) {
......
//1 when非常重要,后续排序和执行和当前时间的比较
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;
}
......
}
return true;
}
- 轮询的时候的处理。看下取Message的MessageQueue的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.
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;
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) {
//当前时间必须大于等于消息执行的时间才能执行,否则设置一个超时时间,nextPollTimeoutMillis暂不分析作用。
//延时作用就提现了,这里会有一个副作用,就是上个消息执行时间过长,等被轮询到,时间早超了,所以postDelay不准的原因在这
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;
}
......
}
}
- 消息延迟,很简单,就是比较当前时间是否过了message.when,但有一点,细心的人发现,计算执行时间点为何不用System.currentTimeMillis(),原型就是这个是系统时间,能随便改,不适合作为时间间隔来计算。
如何处理消息队列为空的情况
这个逻辑的处理还是在MessageQueue.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();
}
//当没有空闲消息执行,nextPollTimeoutMillis = -1,此时会调用epoll机制阻塞该线程,直到消息到来,唤醒该线程
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;
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) {
//当前时间必须大于等于消息执行的时间才能执行,否则设置一个超时时间,nextPollTimeoutMillis暂不分析作用。
//延时作用就提现了,这里会有一个副作用,就是上个消息执行时间过长,等被轮询到,时间早超了,所以postDelay不准的原因在这
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.
// 没有消息的时候,超时时间设置为-1
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.
//当没有消息的时候,会有挽救的机会,就是执行mIdleHandlers里的空闲消息
//IdleHandler是个接口,在sdk中很多地方都有添加,比如在ActivityThread有这么一行代码 Looper.myQueue().addIdleHandler(new Idler());
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);
}
······
// 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,此时可能有消息到来,重新监测
nextPollTimeoutMillis = 0;
}
}
消息队列为空,又没有空闲消息,那么会调用 nativePollOnce(ptr, -1)阻塞线程,是调用linux的epoll 机制来阻塞。在重新插入message的时候会唤醒,代码如下
boolean enqueueMessage(Message msg, long when) {
......
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
//唤醒线程,让线程从nativePollOnce 返回
nativeWake(mPtr);
}
}
return true;
}
这里有个思考,为何使用linux的epoll,epoll的使用场景下多路复用 IO,替换select/poll机制,为何不使用Locker或者wait等java层的锁机制,肯定有深意。原因就是native世界也实现了一套消息通信机制,
为了统一阻塞唤醒机制
native,java两个世界的消息通信的区别和联系
篇幅有限,这个话题用单独的一篇文章来论述 native世界
主线程的loop在哪启动
具体的代码在ActivityThread的main方法中,如下:
public static void main(String[] args) {
......
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
AsyncTask.init();
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
这个main方法是在创建进程的时候,反射调用的,感觉就像是进程的入口,这里不展开,有时间论述ActivityThread的main方法的来弄去脉,顺便也了解进程的启动原理。
这里有个小技巧分享给大家,如果要在非UI线程拿到主线程的栈信息,应该怎么办,这在监控程序中特别有用。答案就是用Loop来获取,具体的代码如下:
Thread thread = Looper.getMainLooper().getThread();
StackTraceElement[] stackTraceElements = thread.getStackTrace();
handler内存泄漏的原理
项目中如果用Lint扫描,如果Handler不是静态内部类,那么会提示Handler可能会造成内存泄漏。泄漏的本质是需要理清一个引用关系,理清道gc roots的引用链,那么问题既可以解决,分析handler内存泄漏的原理