前言
前几天在面试时,被问到了handler机制相关的问题,由于之前对handler机制的了解只是停留在表面,自然也没有回答的上来。想来面试官确实很会引导,而且比较耐心,是我确实对handler原理了解的不够。很感谢他,我下来也专门看了源码参考了一些文章,于今天记录一下。
本文主要有关handler机制的部分源码分析,以及handler使用的简单示例以及handler内存泄漏的解决。
如有错误,敬请指正,感激不尽呀。
正文
定义
什么是handler机制?
总的来讲,handler即是线程间消息传递的机制。
最常见的用途是:由于android规定子线程不可更新UI,所以通常会在子线程中利用handler将要更新UI的消息传递给主线程。
组成
图片来自百度.png如上图所示,handler机制主要由4个部分组成(handlerThread是轻量级异步类,属于对handler类与线程结合的再次封装,在这里暂不讨论):
这里我将顺序打乱,便于将源码之间的逻辑联系起来。
这四个部分分别是:
1.Message
Message则是线程间通信的数据单元,handler会SendMessage,再处理由looper分发过来的Message。
如何构造一个Message?
* <p class="note">While the constructor of Message is public, the best way to get
* one of these is to call {@link #obtain Message.obtain()} or one of the
* {@link Handler#obtainMessage Handler.obtainMessage()} methods, which will pull
* them from a pool of recycled objects.</p>
Message源码注释里指出,尽管Message的构造器是public的,但仍推荐使用Message.obtain()/Handler.obtainMessage()方法来从可复用的Message池中获取一个实例。
那么Message维护了一个怎样的Message复用池呢?
我们先来看下Message.obtain()方法:
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
*/
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();
}
这里涉及到了三个变量:
- public static final Object sPoolSync = new Object();//对象锁
- private static Message sPool;//复用池头部指针
- private static int sPoolSize = 0;//复用池大小
1.锁对象sPoolSync是static final 的Object,obtain()里通过synchronized对象锁来进行线程同步。
2.而最重要的sPool则是一个Message复用池的头部指针
3.sPoolSize则是Message池的大小。
因此Message.obtain()方法是对消息池进行判断,如果为空(即sPool==null),则返回一个新Messgae对象,否则将sPool指向的头Message poll,sPool指向下一个对象。
所以MessagePool是基于链表实现的。
有obtain(),则自然应该有回收的recycle();
/**
* Return a Message instance to the global pool.
* <p>
* You MUST NOT touch the Message after calling this function because it has
* effectively been freed. It is an error to recycle a message that is currently
* enqueued or that is in the process of being delivered to a Handler.
* </p>
*/
public void recycle() {
if (isInUse()) {
if (gCheckRecycle) {
throw new IllegalStateException("This message cannot be recycled because it "
+ "is still in use.");
}
return;
}
recycleUnchecked();
}
recyle()函数主要是检查了一下messgae是否正在被使用,如未被使用,则将其回收(这种检查未必生效,因为recycleUnchecked()里指出回收的对象仍有可能是in-Use)。注释里特别指出,对正在队列中和正在被分发给handler的Message回收是错误的!
再来看一下recycleUnchecked()方法:
/**
* Recycles a Message that may be in-use.
* Used internally by the MessageQueue and Looper when disposing of queued Messages.
*/
@UnsupportedAppUsage
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++;
}
}
}
这个应该没有什么特别疑问的地方,注释里也写的很清楚了,会将标志位标为正在使用并将其他信息进行清除,然后如果MessagePool的大小小于规定的最大数量,则将其加到链表头。
MAX_POOL_SIZE在规定中是 private static final int MAX_POOL_SIZE = 50;
2.handler
* <p>There are two main uses for a Handler: (1) to schedule messages and
* runnables to be executed at some point in the future; and (2) to enqueue
* an action to be performed on a different thread than your own.
这里直接引用handler源码注释,总的来讲,handler主要的作用是将来自不同线程的消息/动作入队,以及对未来将要运行的消息/动作进行调度处理。
既然前面已经写了Message的构造和复用,那handler就从handler.sendMessage()开始看起吧。
/**
* Pushes a message onto the end of the message queue after all pending messages
* before the current time. It will be received in {@link #handleMessage},
* in the thread attached to this handler.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public final boolean sendMessage(@NonNull Message msg) {
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
实际最终调用的是sendMessageAtTime,sendMessage与sendMessageDelayed这两个方法没有什么特别要讲的,我们主要看一下sendMessageAtTime方法:
/**
* Enqueue a message into the message queue after all pending messages
* before the absolute time (in milliseconds) <var>uptimeMillis</var>.
* <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
* Time spent in deep sleep will add an additional delay to execution.
* You will receive it in {@link #handleMessage}, in the thread attached
* to this handler.
*
* @param uptimeMillis The absolute time at which the message should be
* delivered, using the
* {@link android.os.SystemClock#uptimeMillis} time-base.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the message will be processed -- if
* the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*/
public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
mQueue即是handler所对应的messageQueue,每个Handler只能对应一个messageQueue。这里判断如果messageQueue为空,则抛出运行时异常,否则将消息入队。需要注意的是:注释中指出,即使enqueueMessage(queue, msg, uptimeMillis)结果返回为true,也不意味着message就会被处理,因为looper可能在消息被分发之前就退出了,那时Message将被抛弃。
接下来看一下上面使用到的enqueueMessage方法:
private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
long uptimeMillis) {
msg.target = this;
msg.workSourceUid = ThreadLocalWorkSource.getUid();
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
主要是设置了target和orkSourceUid、mAsynchronous异步标志位,然后调用MessageQueued的enqueueMessage方法将其入队。enqueueMessage方法详见MessageQueue部分。
这里要插播一点代码:
前面提到Handler要将消息入队并且承担着处理Messgae的责任。
那这里就是Handler处理Message的地方了:
/**
* Handle system messages here.
*/
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
dipatch的意思是分发,这里就是根据不同情况来对message进行处理。
如果msg.callback不为空,则调用message.callback.run();
如果mCallback不为空,则调用mCallback.handleMessage(msg)。
msg.callback和mCallback都为空,则调用handleMessage(msg)方法,这个方法默认是空实现,需要程序员来重写。
上面提到的mCallback是一个可设置的接口
/**
* Callback interface you can use when instantiating a Handler to avoid
* having to implement your own subclass of Handler.
*/
public interface Callback {
/**
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is desired
*/
boolean handleMessage(@NonNull Message msg);
}
是通过回调接口来避免实现一个handler的子类。
3.MessageQueue
消息队列,负责存储handler发送过来的消息,采用链表存储。
MessageQueue主要看一下上面提到的enqueue方法:
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;
}
首先对msg的携带的信息进行判断,target为空则没有对应的handler,msg.isInUse()为真则说明msg正在使用,自然都该抛出对应的异常。
需要注意的是对消息的入队操作是加了同步对象锁进行了同步处理的,mMessages始终指向MessageQueue的链表头,message入队时会根据when的时间顺序来入队,如果when==0说明要立即执行,则直接将其放到队头,否则遍历链表,根据when的大小顺序插入到相应的位置。
4.Looper
循环器,负责循环从MessageQueue中取消息,并将消息分发给应对其处理的handler。
关于looper,主要看一下loop方法:
/**
* 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;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
// Allow overriding a threshold with a system prop. e.g.
// adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
final int thresholdOverride =
SystemProperties.getInt("log.looper."
+ Process.myUid() + "."
+ Thread.currentThread().getName()
+ ".slow", 0);
boolean slowDeliveryDetected = false;
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
// Make sure the observer won't change while processing a transaction.
final Observer observer = sObserver;
final long traceTag = me.mTraceTag;
long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
if (thresholdOverride > 0) {
slowDispatchThresholdMs = thresholdOverride;
slowDeliveryThresholdMs = thresholdOverride;
}
final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);
final boolean needStartTime = logSlowDelivery || logSlowDispatch;
final boolean needEndTime = logSlowDispatch;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
final long dispatchEnd;
Object token = null;
if (observer != null) {
token = observer.messageDispatchStarting();
}
long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);
try {
msg.target.dispatchMessage(msg);
if (observer != null) {
observer.messageDispatched(token, msg);
}
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} catch (Exception exception) {
if (observer != null) {
observer.dispatchingThrewException(token, msg, exception);
}
throw exception;
} finally {
ThreadLocalWorkSource.restore(origWorkSource);
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logSlowDelivery) {
if (slowDeliveryDetected) {
if ((dispatchStart - msg.when) <= 10) {
Slog.w(TAG, "Drained");
slowDeliveryDetected = false;
}
} else {
if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
msg)) {
// Once we write a slow delivery log, suppress until the queue drains.
slowDeliveryDetected = true;
}
}
}
if (logSlowDispatch) {
showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
}
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
msg.recycleUnchecked();
}
}
每个线程的looper存储在对应线程的ThreadLocal中,loop()会不断循环调用messageQueue的next()取出消息,然后分发给对应的taget进行dispatch。
截取部分next()源码:
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;
}
会发现大概思路是如果存在异步消息(有同步屏障),则取出异步消息。否则直接取出队头的同步消息。
使用
最常见的使用,这里写了一个子线程通知主线程更新ui的demo:
public class MainActivity extends AppCompatActivity {
private Handler mHandler;//leak
private static final String TAG = "MainActivity";
private final static int MSG_CHANGE_TEXT = 0 ;
private Activity activity ;
@SuppressLint("HandlerLeak")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity=this;
mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case MSG_CHANGE_TEXT:
//do somenthing
Log.d(TAG,"Get Message i am going to change UI");
break;
default:
break;
}
}
};
new Thread(new Runnable() {
@Override
public void run() {
Message message1 =Message.obtain();
message1.what=MSG_CHANGE_TEXT;
mHandler.sendMessage(message1);
}
}).start();
}
}
我们创建了一个匿名内部类Handler。需注意我们在OnCreate前添加了@SuppressLint("HandlerLeak")注解,是因为这种写法可能会导致内存泄漏,加上一个注解来忽略Lint错误。
为什么会导致内存泄漏?
是因为前面创建handler的时候是采用了创建匿名内部类的方式,而匿名内部类会隐式地持有外部类的引用。
如果handler没有被释放,那么作为它所持有的外部引用Activity自然也不会被释放。
比如用Handler post一个delay的消息,在消息未发送前将Activity退出,表面上好像activity应该被回收了。实际handler仍然存活,它的外部引用activity则不会被回收,从而引起内存泄漏。
如何解决内存泄漏?
解决内存泄漏的方法比较推荐的是使用静态内部类的方式(当然也可以用handler.removeCallbacksAndMessages(null),只要程序员不会忘了在对应的生命周期调用并且这种调用时机是正确的),写了一个demo如下:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private final static int MSG_CHANGE_TEXT = 0 ;
private Activity activity ;
private MyHandler myHandler;
private static class MyHandler extends Handler{
private WeakReference<MainActivity> mActivity ;
public MyHandler(@NonNull MainActivity activity){
mActivity=new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(mActivity.get()==null){
return;
}
switch (msg.what){
case MSG_CHANGE_TEXT:
//do somenthing
Log.d(TAG,"Get Message i am going to change UI");
break;
default:
break;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myHandler=new MyHandler(this);
new Thread(new Runnable() {
@Override
public void run() {
Message message1 =Message.obtain();
message1.what=MSG_CHANGE_TEXT;
myHandler.sendMessage(message1);
}
}).start();
}
}
主要的思路就是把handler变为静态内部类,静态内部类不会持有外部类的引用。如果需要在静态内部类中使用外部类,可以持有一个外部类的弱引用。
没有设置looper?
前面的例子,我们创建主线程初始化handler时都没有指定对应的looper。为什么我们在主线程里初始化handler的时候不需要指定looper呢?
我们来看下app的入口(即ActivityThread里的main方法。ActivityThread准确地说不是主线程,它也并不是一个线程类。运行ActivityThread的才是主线程)
public static void main(String[] args) {
/......../
Looper.prepareMainLooper();
/......../
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
实际上在app启动时,就已经为我们的主线程设置一个mainLooper()。
后记
终于写完这篇了,不过感觉还是有些遗漏的地方,有些过程仍不够直观。不过大致思路是有了,有空再修改...
本文参考:
https://www.jianshu.com/p/b4d745c7ff7a
https://blog.csdn.net/javazejian/article/details/50839443
网友评论