前言
前幾天在面試時(shí),被問到了handler機(jī)制相關(guān)的問題,由于之前對handler機(jī)制的了解只是停留在表面,自然也沒有回答的上來。想來面試官確實(shí)很會引導(dǎo),而且比較耐心,是我確實(shí)對handler原理了解的不夠。很感謝他,我下來也專門看了源碼參考了一些文章,于今天記錄一下。
本文主要有關(guān)handler機(jī)制的部分源碼分析,以及handler使用的簡單示例以及handler內(nèi)存泄漏的解決。
如有錯(cuò)誤,敬請指正,感激不盡呀。
正文
定義
什么是handler機(jī)制?
總的來講,handler即是線程間消息傳遞的機(jī)制。
最常見的用途是:由于android規(guī)定子線程不可更新UI,所以通常會在子線程中利用handler將要更新UI的消息傳遞給主線程。
組成

如上圖所示,handler機(jī)制主要由4個(gè)部分組成(handlerThread是輕量級異步類,屬于對handler類與線程結(jié)合的再次封裝,在這里暫不討論):
這里我將順序打亂,便于將源碼之間的邏輯聯(lián)系起來。
這四個(gè)部分分別是:
1.Message
Message則是線程間通信的數(shù)據(jù)單元,handler會SendMessage,再處理由looper分發(fā)過來的Message。
如何構(gòu)造一個(gè)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的構(gòu)造器是public的,但仍推薦使用Message.obtain()/Handler.obtainMessage()方法來從可復(fù)用的Message池中獲取一個(gè)實(shí)例。
那么Message維護(hù)了一個(gè)怎樣的Message復(fù)用池呢?
我們先來看下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();
}
這里涉及到了三個(gè)變量:
- public static final Object sPoolSync = new Object();//對象鎖
- private static Message sPool;//復(fù)用池頭部指針
- private static int sPoolSize = 0;//復(fù)用池大小
1.鎖對象sPoolSync是static final 的Object,obtain()里通過synchronized對象鎖來進(jìn)行線程同步。
2.而最重要的sPool則是一個(gè)Message復(fù)用池的頭部指針
3.sPoolSize則是Message池的大小。
因此Message.obtain()方法是對消息池進(jìn)行判斷,如果為空(即sPool==null),則返回一個(gè)新Messgae對象,否則將sPool指向的頭Message poll,sPool指向下一個(gè)對象。
所以MessagePool是基于鏈表實(shí)現(xiàn)的。
有obtain(),則自然應(yīng)該有回收的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()函數(shù)主要是檢查了一下messgae是否正在被使用,如未被使用,則將其回收(這種檢查未必生效,因?yàn)閞ecycleUnchecked()里指出回收的對象仍有可能是in-Use)。注釋里特別指出,對正在隊(duì)列中和正在被分發(fā)給handler的Message回收是錯(cuò)誤的!
再來看一下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++;
}
}
}
這個(gè)應(yīng)該沒有什么特別疑問的地方,注釋里也寫的很清楚了,會將標(biāo)志位標(biāo)為正在使用并將其他信息進(jìn)行清除,然后如果MessagePool的大小小于規(guī)定的最大數(shù)量,則將其加到鏈表頭。
MAX_POOL_SIZE在規(guī)定中是 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主要的作用是將來自不同線程的消息/動作入隊(duì),以及對未來將要運(yùn)行的消息/動作進(jìn)行調(diào)度處理。
既然前面已經(jīng)寫了Message的構(gòu)造和復(fù)用,那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);
}
實(shí)際最終調(diào)用的是sendMessageAtTime,sendMessage與sendMessageDelayed這兩個(gè)方法沒有什么特別要講的,我們主要看一下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所對應(yīng)的messageQueue,每個(gè)Handler只能對應(yīng)一個(gè)messageQueue。這里判斷如果messageQueue為空,則拋出運(yùn)行時(shí)異常,否則將消息入隊(duì)。需要注意的是:注釋中指出,即使enqueueMessage(queue, msg, uptimeMillis)結(jié)果返回為true,也不意味著message就會被處理,因?yàn)閘ooper可能在消息被分發(fā)之前就退出了,那時(shí)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);
}
主要是設(shè)置了target和orkSourceUid、mAsynchronous異步標(biāo)志位,然后調(diào)用MessageQueued的enqueueMessage方法將其入隊(duì)。enqueueMessage方法詳見MessageQueue部分。
這里要插播一點(diǎn)代碼:
前面提到Handler要將消息入隊(duì)并且承擔(dān)著處理Messgae的責(zé)任。
那這里就是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的意思是分發(fā),這里就是根據(jù)不同情況來對message進(jìn)行處理。
如果msg.callback不為空,則調(diào)用message.callback.run();
如果mCallback不為空,則調(diào)用mCallback.handleMessage(msg)。
msg.callback和mCallback都為空,則調(diào)用handleMessage(msg)方法,這個(gè)方法默認(rèn)是空實(shí)現(xiàn),需要程序員來重寫。
上面提到的mCallback是一個(gè)可設(shè)置的接口
/**
* 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);
}
是通過回調(diào)接口來避免實(shí)現(xiàn)一個(gè)handler的子類。
3.MessageQueue
消息隊(duì)列,負(fù)責(zé)存儲handler發(fā)送過來的消息,采用鏈表存儲。
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的攜帶的信息進(jìn)行判斷,target為空則沒有對應(yīng)的handler,msg.isInUse()為真則說明msg正在使用,自然都該拋出對應(yīng)的異常。
需要注意的是對消息的入隊(duì)操作是加了同步對象鎖進(jìn)行了同步處理的,mMessages始終指向MessageQueue的鏈表頭,message入隊(duì)時(shí)會根據(jù)when的時(shí)間順序來入隊(duì),如果when==0說明要立即執(zhí)行,則直接將其放到隊(duì)頭,否則遍歷鏈表,根據(jù)when的大小順序插入到相應(yīng)的位置。
4.Looper
循環(huán)器,負(fù)責(zé)循環(huán)從MessageQueue中取消息,并將消息分發(fā)給應(yīng)對其處理的handler。
關(guān)于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();
}
}
每個(gè)線程的looper存儲在對應(yīng)線程的ThreadLocal中,loop()會不斷循環(huán)調(diào)用messageQueue的next()取出消息,然后分發(fā)給對應(yīng)的taget進(jìn)行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;
}
會發(fā)現(xiàn)大概思路是如果存在異步消息(有同步屏障),則取出異步消息。否則直接取出隊(duì)頭的同步消息。
使用
最常見的使用,這里寫了一個(gè)子線程通知主線程更新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();
}
}
我們創(chuàng)建了一個(gè)匿名內(nèi)部類Handler。需注意我們在OnCreate前添加了@SuppressLint("HandlerLeak")注解,是因?yàn)檫@種寫法可能會導(dǎo)致內(nèi)存泄漏,加上一個(gè)注解來忽略Lint錯(cuò)誤。

為什么會導(dǎo)致內(nèi)存泄漏?
是因?yàn)榍懊鎰?chuàng)建handler的時(shí)候是采用了創(chuàng)建匿名內(nèi)部類的方式,而匿名內(nèi)部類會隱式地持有外部類的引用。
如果handler沒有被釋放,那么作為它所持有的外部引用Activity自然也不會被釋放。
比如用Handler post一個(gè)delay的消息,在消息未發(fā)送前將Activity退出,表面上好像activity應(yīng)該被回收了。實(shí)際handler仍然存活,它的外部引用activity則不會被回收,從而引起內(nèi)存泄漏。
如何解決內(nèi)存泄漏?
解決內(nèi)存泄漏的方法比較推薦的是使用靜態(tài)內(nèi)部類的方式(當(dāng)然也可以用handler.removeCallbacksAndMessages(null),只要程序員不會忘了在對應(yīng)的生命周期調(diào)用并且這種調(diào)用時(shí)機(jī)是正確的),寫了一個(gè)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變?yōu)殪o態(tài)內(nèi)部類,靜態(tài)內(nèi)部類不會持有外部類的引用。如果需要在靜態(tài)內(nèi)部類中使用外部類,可以持有一個(gè)外部類的弱引用。
沒有設(shè)置looper?
前面的例子,我們創(chuàng)建主線程初始化handler時(shí)都沒有指定對應(yīng)的looper。為什么我們在主線程里初始化handler的時(shí)候不需要指定looper呢?
我們來看下app的入口(即ActivityThread里的main方法。ActivityThread準(zhǔn)確地說不是主線程,它也并不是一個(gè)線程類。運(yùn)行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");
}
實(shí)際上在app啟動時(shí),就已經(jīng)為我們的主線程設(shè)置一個(gè)mainLooper()。
后記
終于寫完這篇了,不過感覺還是有些遺漏的地方,有些過程仍不夠直觀。不過大致思路是有了,有空再修改...
本文參考:
http://www.itdecent.cn/p/b4d745c7ff7a
https://blog.csdn.net/javazejian/article/details/50839443