Handler构造方法
- 在Handler存在多个重载构造方法,最终执行到下面2个重载构造方法中的一个,目的都是为了初始化下面的四个参数
// 法1:
public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
// 法2:
public Handler(@Nullable Callback callback, boolean async) {
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
考点:当我们在子线程中new Hanlder时,运行报错,则就是执行到了法2的构造方法中
Looper构造方法
- 在Looper构造方法中,会创建一个MessageQueue对象,用于后面存放消息,并且Looper的构造方法是私有的,外部无法通过new去创建,提供了静态方法prepare创建
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
核心API
Handler
- sendMessage:发送消息等一系列方法最终都是执行sendMessageDelay方法
- enqueueMessage:将消息发送到消息MessageQueue队列中,等待处理,该方法涉及到3个核心点,见代码注释
private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
long uptimeMillis) {
// 核心点1:将当前handler引用保存到message中,用于后面拿到message时,
// 将message发送到handler中处理
msg.target = this;
msg.workSourceUid = ThreadLocalWorkSource.getUid();
if (mAsynchronous) {
// 核心点2: 用于发送同步消息屏障(后面会单独说),执行异步消息的关键步骤
msg.setAsynchronous(true);
}
// 核心点3:将消息存放到消息队列中,等待杯处理
return queue.enqueueMessage(msg, uptimeMillis);
}
考点:在Handler.enqueueMessage()中会将当前的handler对象保存到Message.target中,这是Handler内存泄露的主要原因
- post:与sendMessage一样最终也是发送一个message到消息队列中,不一致的是,post接受的是一个Runnable对象,然后在包装到Message.callback的Runnable对象中,后面与sendMessage流程一致
public final boolean post(@NonNull Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
- dispatchMessage:分发消息,就是在looper中拿到message中,通过Message.target.dispatchMessage将消息分发到handler中处理
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
考点:针对不同的消息发送方式,最终在handler中处理的时也分优先级,post>Handler.mCallback>sendMessage,根据这个特性,这里是一个hook点
MessageQueue
- enqueueMessage:将消息按等待时长的顺序,存放到队列中
boolean enqueueMessage(Message msg, long when) {
...
synchronized (this) {
...
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 {
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;
}
考点:当消息队列中暂无可处理的消息时,不会因为无限死循环导致消耗CPU资源,而是会释放资源,进入休眠,当有新消息进入后,会执行 nativeWake 唤醒主线程
-
同步屏障与异步消息:
1、同步屏障:是一个target==null的消息,当处理到同步屏障消息时,会阻塞正常的消息执行,而是找出所有异步消息并处理,当异步消息执行完毕后,如果未移出屏障,则消息机制会进入休眠,即使同步消息未执行完,也不会继续执行,直到移除同步屏障,方可继续执行同步消息
2、异步消息:则是Message.setAsynchronous设置true,需要配合同步屏障一起使用方可优先执行异步消息 -
next:从消息队列中取消息,根据需要延长的时长执行nativePollOnce进行等待。
如果当前是非同步屏障消息,则正常按顺序取出消息执行
如果当前时同步屏障消息,则暂停获取队列中的同步消息,而是优先获取队列中异步消息
Message next() {
// 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;
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;
}
...
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;
}
...
}
...
}
}
考点:nextPollTimeoutMillis==-1,表示当前暂无消息可处理,执行nativePollOnce释放cup进入休眠,等待enqueueMessage中执行nativeWake唤醒
- postSyncBarrier:发送一个同步屏障消息到消息队列中,该消息是无赋值target对象的,并且无等待时长
- removeSyncBarrier:移除同步屏障消息,否则异步消息执行完毕后,同步消息依旧无法执行
Message
- obtain:静态方法创建一个消息,优先从消息池中复用,如果没有可复用的,则new Message,消息池中最大容量是50(android-31的源码中)
private static final int MAX_POOL_SIZE = 50;
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
- recycleUnchecked:消息回收,将已经处理过的message中内部属性重置,并将回收的消息放到消息池中
void recycleUnchecked() {
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++;
}
}
}
Looper
- prepare:静态方法提供给外部创建Looper对象,在创建前,会校验当前线程是否有绑定Looper对象
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
- loop:静态方法,开启无限循环从消息队列中获取消息,然后分发到handler中处理
public static void loop() {
...
for (;;) {
if (!loopOnce(me, ident, thresholdOverride)) {
return;
}
}
}
private static boolean loopOnce(final Looper me,
final long ident, final int thresholdOverride) {
// 核心1:从消息队列中取
Message msg = me.mQueue.next(); // might block
...
// 核心2:消息分发到handler处理
msg.target.dispatchMessage(msg);
...
// 核心3:消息回收
msg.recycleUnchecked();
return true;
}
ThreadLocal
- set:用于以ThreadLocal为key与value保存到当前线程中的ThreadLocalMap中
- get:用于从当前线程中的ThreadLocalMap中以ThreadLocal为key查找出value
考点1:Thread、ThreadLocal、ThreadLocalMap之间的关系:
ThreadLocalMap是Thread中的变量,是通过ThreadLocal.createMap创建的
ThreadLocal是以key的形式与value形成键值对存放到ThreadLocalMap中
考点2:ThreadLocal为何线程安全:因为在每个线程中ThreadLocal都存有新的副本,做到了线程间数据隔离,原因是因为无论是从ThreadLocal中存还是取,都是从当前线程中ThreadLocalMap中取对应的ThreadLocal的值
ThreadLocalMap
- 算法:其内部有一个table数组,用于存放Entry的一个虚饮用,默认容量16,会根据key的hash值&运算一个table数组大小-1 <=等价=> key.hashCode % table.length-1,这样就可以根据key来生成一个在table上的一个索引,然后存放对应的Entry,如果该位置已经有元素,会判断key是否一致,不一致,则往下遍历找到一个空的位置存放Entry