注册

Handler 源码分析

Handler源码的学习理解

一.相关类说明

1.Handler作用

①实现线程切换,可以在A个线程使用B线程创建的Handler发送消息,然后在B线程的Handler handleMessage回调中接收A线程的消息。

②实现发送延时消息 hanlder.postDelay(),sendMessageDelayed()

2.Message

消息的载体,包含发送的handler对象等信息,Message本身是一个单链表结构,里面维护了next Message对象;内部维护了一个Message Pool,使用时调用Message.obtain()方法来从Message 池子中获取对象,可以让我们在许多情况下避免new对象,减少内存开,Message种类有普通message,异步Message,同步屏障Message。

3.MessageQueue

MessageQueue:一个优先级队列,内部是一个按Message.when从小到大排列的Message单链表;可以通过enqueueMessage()添加Message,通过next()取出Message,但是必须配合Handler与Looper来实现这个过程。

4.Looper

通过Looper.prepare()去创建一个Looper,调用Looper.loop()去不断轮询MessageQueue队列,调用MessageQueue 的next()方法直到取出Msg,然后回调msg.target.dispatchMessage(msg);实现消息的取出与分发。

二.原理分析

我们在MainActivity的成员变量初始化一个Handler,然后子线程通过handler post/send msg发送一个消息 ,最后我们在主线程的Handler回调handleMessage(msg: Message)拿到我们的消息。理解了这个从发送到接收的过程,Handler原理就掌握的差不多了。下面来分析这个过程:

1.发送消息

handler post/send msg 对象到 MessageQueue ,无论调用Handler哪个发送方法,最后都会调用到Handler.enqueueMessage()方法:

 private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,long uptimeMillis) {
//handler enqueneMessage 将handler赋值给msg.target,为了区分消息队列的消息属于哪个handler发送的
msg.target = this;
msg.workSourceUid = ThreadLocalWorkSource.getUid();

if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
复制代码

然后再去调用MessageQueue.enqueueMessage(),将Message按照message 的when参数的从小到大的顺序插入到MessageQueue中.MessageQueue是一个优先级队列,内部是以单链表的形式存储Message的。这样我们完成了消息发送到MessageQueue的步骤。

boolean enqueueMessage(Message msg, long when) {
//、、、、、、
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
//when == 0 就是直接发送的消息 将msg插到队列的头部
// 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;
//准备插入的msg.when 时间小于队列中某个消息的when 就跳出循环
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
//插入msg 到队列中这个消息的前面
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;
}
复制代码

2.取出消息

我们知道消息队列MessageQueue是死的,它不会自己去取出某个消息的。所以我们需要一个让MessageQueue动起来的动力--Looper.首先创建一个Looper,代码如下:

 //Looper.java    
// sThreadLocal.get() will return null unless you've called prepare().
@UnsupportedAppUsage
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static void prepare(boolean quitAllowed) {
//sThreadLocal.get() 得到Looper 不为null
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}

//ThreadLocal.java
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
//将thread本身最为key, looper为value存在ThreadLocalMap中
map.set(this, value);
else
createMap(t, value);
}
复制代码

从源码可以看出,一个线程只能存在一个Looper,接着来看looper.loop()方法,主要做了取message的工作:

//looper.java  
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/

public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;
//..............
//死循环取出message
for (;;) {
Message msg = queue.next(); // might block 调用MessageQueue的next()方法取出消息,可能发生阻塞
if (msg == null) {//msg == null 代表message queue 正在退出,一般不会为null
// No message indicates that the message queue is quitting.
return;
}
//...............
try {//取出消息后,分发给对应的 msg.target 也就是handler
msg.target.dispatchMessage(msg);
// 、、、、、
} catch (Exception exception) {
// 、、、、、
} finally {
// 、、、、、
}
// 、、、、、重置属性并回收message到复用池
msg.recycleUnchecked();
}
}
//Message.java
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 = UID_NONE;
workSourceUid = UID_NONE;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
复制代码

3.MessageQueue的next()方法

不断的从消息队列里拿消息,如果有异步消息,先所有的异步消息放在队列的前面优先执行,然后,拿到同步消息,分发给对应的handler,在MessageQueue中没有消息要执行时即MessageQueue空闲时,如果有idelHandler则会去执行idelHandler 的任务,通过idler.queueIdle()处理任务.

  //MessageQueue.java
Message next() {
//........
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;//mMessages保存链表的第一个元素
if (msg != null && msg.target == null) {//当有屏障消息时,就去寻找最近的下一个异步消息

// msg.target == null 时为屏障消息(参考MessageQueue.java 的postSyncBarrier()),找到寻找下一个异步消息
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;//记录prevMsg为异步消息的前一个同步消息

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 {//无屏障消息直接取出这个消息,并重置MessageQueue队列的头
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
//返回队列的一个message
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)) {
//当消息对列没有要执行的message时,去赋值pendingIdleHandlerCount
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}

if (mPendingIdleHandlers == null) {
//创建 IdleHandler[]
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 {
//执行IdleHandle[]的每个queueIdle(),Return true to keep your idle handler active
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}

if (!keep) {//mIdleHandlers 被删除了
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;
}
}
复制代码

三.常见问题

通过以上源码的分析,了解到Handler的工作原理,根据原理可回答出一下几个经典题目:

1.一个线程有几个handler?

可以有多个handler,因为可以在一个线程 new多个handler ,并且handler 发送message时,会将handler 赋值给message.target

2.一个线程有几个looper?如何保证?

只能有一个,否则会抛异常

3.Handler内存泄漏原因?为什么其他的内部类没有说过这个问题?

Handler内存泄漏的根本原因时在于延时消息,因为Handler 发送一个延时消息到MessageQueue,MessageQueue中持有的Message中持有Handler的引用,而Handler作为Activity的内部类持有Activity的引用,所以当Activity销毁时因MessageQueue的Message无法释放,会导致Activity无法释放,造成内存泄漏

4.为何主线程可以new Handler?如果想在子线程中new Handler要做哪些准备?

因为APP启动后ActivityThread会帮我们自动创建Looper。如果想在子线程中new Handler要做调用Looper.prepare(),Looper.loop()方法

//ActivityThread.java    
public static void main(String[] args) {


Looper.prepareMainLooper();
//............
Looper.loop();

throw new RuntimeException("Main thread loop unexpectedly exited");
}
复制代码

5.子线程维护的Looper,消息队列无消息时,处理方案是什么?有什么用?

子线程中new Handler要做调用Looper.prepare(),Looper.loop()方法,并在结束时手动调用Looper.quit(),LooperquitSafely()方法来终止Looper,否则子线程会一直卡死在这个阻塞状态不能停止

6.既然可以存在多个Handler往MessageQueue中添加数据(发消息时各个Handler可以能处于不同线程),那他内部如何保证线程安全的?

 boolean enqueueMessage(Message msg, long when) {
//..............通过synchronized保证线程安全
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;
}
//..............
}
复制代码

7.我们使用Message时应该如何创建它?

Message.obtain()

8.使用Handler的postDelay后消息队列会有什么变化?

按照Message.when 插入message

9.Looper死循环为啥不会导致应用卡死

Looper死循环,没消息会进行休眠不会卡死调用linux底层的epoll机制实现;应用卡死时是ANR导致的;两者是不一样的概念

ANR:用户输入事件或者触摸屏幕5S没响应或者广播在10S内未执行完毕,Service的各个生命周期函数在特定时间(20秒)内无法完成处理

0 个评论

要回复文章请先登录注册