Handler源碼分析

Handler:

Handler主要是用于異步消息的處理:當(dāng)發(fā)出一個(gè)消息之后,首先進(jìn)入一個(gè)消息隊(duì)列,發(fā)送消息的函數(shù)即刻返回,而另外一部分在消息隊(duì)列中逐一將消息取出,然后對(duì)消息進(jìn)行處理。

問題:
  1. Handler(Callback) 跟 Handler() 這兩個(gè)構(gòu)造方法的區(qū)別在哪, Handler什么情況下會(huì)內(nèi)存泄漏?
  2. 刷新UI為什么只能在主線程中執(zhí)行
  3. 為什么創(chuàng)建 Message 對(duì)象推薦使用 Message.obtain()獲???
  4. Threadlocal用法和原理
  5. 為什么 Handler 能夠切換線程執(zhí)行?
  6. Looper.loop() 為什么不會(huì)造成應(yīng)用卡死?
問題1
   Handler handler2 = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
        }
    };

但是這樣會(huì)報(bào)黃色警告。大體意思就是說handler應(yīng)該為靜態(tài)。否則會(huì)造成內(nèi)存泄漏。
MessageQueue中的消息隊(duì)列會(huì)一直持有對(duì)handler的引用,而作為內(nèi)部類的handler會(huì)一直持有外部類的引用,就會(huì)導(dǎo)致外部類不能被GC回收。當(dāng)我們發(fā)延時(shí)很長的msg時(shí)就容易出現(xiàn)泄漏。

1.新建靜態(tài)類繼承Handler.
所以此處應(yīng)該設(shè)置為static,然后Handler就會(huì)跟隨類而不是跟隨類的對(duì)象加載,也就不再持有外部類的對(duì)象引用。

2.使用Handler.Callback()

   Handler handler1 = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            return false; 
        }
    });
  /**
     * 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);
    }

     /**
     * Handle system messages here.
     */
    public void dispatchMessage(@NonNull Message msg) {
        if (msg.callback != null) {  //若callback不為空,代表使用post(Runnable r)發(fā)送消息
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);//創(chuàng)建Handler實(shí)例時(shí)復(fù)寫
        }
    }

問題二: 刷新UI為什么只能在主線程中執(zhí)行

問題三:為什么創(chuàng)建 Message 對(duì)象推薦使用 Message.obtain()獲?。?/h4>
/**
     * 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;  //spool指向下一個(gè)緩存對(duì)象
                 m.next = null;
                 m.flags = 0; // clear in-use flag
                 sPoolSize--;
                 return m;
            }
        }
        return new Message();
    }
image.png

sPool 消息緩存池,若消息池不為空,則從頭節(jié)點(diǎn)取出,置為非使用狀態(tài)。若消息池為空,則新建一個(gè)Message。

private static final int MAX_POOL_SIZE = 50;
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++;
            }
        }
    }
image.png

在Looper.loop()方法中,當(dāng)msg消息處理完畢,則會(huì)調(diào)用上面Message的回收方法,將消息的參數(shù)清空,若消息池的數(shù)量少于50,則將消息插入緩存池的頭結(jié)點(diǎn)。

問題四:Threadlocal用法和原理

ThreadLocal.java
  public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

   public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
  void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

可以看到上面代碼,在存儲(chǔ)和取 是以當(dāng)前線程為key,looper為value。 在Handler初始化的時(shí)候會(huì)檢查是否能取到looper,否則拋出異常!

ThreadLocal的作用是不同的線程擁有該線程獨(dú)立的變量,同名對(duì)象不會(huì)被受到不同線程間相互使用出現(xiàn)異常的情況。
即:你的程序擁有多個(gè)線程,線程中要用到相同的對(duì)象,但又不允許線程之間操作同一份對(duì)象。那么就可以使用ThreadLocal來解決。它可以在線程中使用mThreadLocal.get()和mThreadLocal.set()來使用。若未被在當(dāng)前線程中調(diào)用set方法,那么get時(shí)為空。

image.png

問題五:為什么 Handler 能夠切換線程執(zhí)行?

image.png

Handler 發(fā)送的線程不處理消息,只有Looper.loop()將消息取出來后再進(jìn)行處理,所以在Handler機(jī)制中,無論發(fā)送消息的Handler對(duì)象處于什么線程,最終的處理都是運(yùn)行在 Looper.loop() 所在的線程。

問題六:Looper.loop() 為什么不會(huì)造成應(yīng)用卡死?

這里我們先看張流程圖:


image.png

MessageQueue.java

boolean enqueueMessage(Message msg, long when) {  //when = SystemClock.uptimeMillis() + delayMillis
     ...
        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;    //賦值調(diào)用時(shí)間
            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 (; ; ) { //根據(jù)消息(Message)創(chuàng)建時(shí)間插入到隊(duì)列中
                    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ù)當(dāng)前是否有message需要返回和messge的執(zhí)行時(shí)間(when)排序。


image.png

這里mMessages不為空時(shí)為當(dāng)前鏈表的第一個(gè)Message,當(dāng)有message需要執(zhí)行的時(shí)候,會(huì)調(diào)用
nativeWake(mPtr)方法,(將主線程喚醒)

這里L(fēng)ooper.loop()方法時(shí)一直在主線程循環(huán)的執(zhí)行的。

public static void loop() {
        final Looper me = myLooper();
        ...
        final MessageQueue queue = me.mQueue;
        ...
        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                return;
            }
            ...
            msg.target.dispatchMessage(msg);  //派發(fā)消息到對(duì)應(yīng)的Handler
            ...
        }
    }

這里面主要是next方法。msg.target為 Handler。會(huì)將從messageQueue中取message傳遞出去。
下面看下 dispatchMessage方法

**Handler.class**
 public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

dispatchMessage方法里面針對(duì) Handler發(fā)送Message方式做了處理。
下面重點(diǎn)看看下next()方法。取消息的方法。

 Message next() {
      ...
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;  ////阻塞時(shí)間:-1是一直阻塞不超時(shí);0是不會(huì)阻塞,立即返回;大于0則nextPollTimeoutMillis是最長阻塞時(shí)間,期間有線程喚醒立即返回
        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) {  //when是消息傳遞的目標(biāo)時(shí)間
                        // 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);//計(jì)算消息等待時(shí)間
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;// 清除next
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;   // 若 消息隊(duì)列中已無消息,則將nextPollTimeoutMillis參數(shù)設(shè)為-1 下次循環(huán)時(shí),消息隊(duì)列則處于等待狀態(tài)
                }
        ...
        }
    }

nextPollTimeoutMillis:

-1是一直阻塞不超時(shí);
0是不會(huì)阻塞,立即返回;
大于0則nextPollTimeoutMillis是最長阻塞時(shí)間,期間有線程喚醒立即返回

1.若當(dāng)前取出的mMessage為空,則將nextPollTimeoutMillis置為-1,然后調(diào)用 nativePollOnce(ptr, nextPollTimeoutMillis);會(huì)將線程阻塞在這里。
2.若當(dāng)前取出消息時(shí)間還沒到,則計(jì)算出需要等待時(shí)間,阻塞線程
3.將消息的next置為null,給mMessages = msg.next;賦于下一個(gè)msg。并將message返回出去。

特別注意

  • 1個(gè)線程(Thread)只能綁定 1個(gè)循環(huán)器(Looper),但可以有多個(gè)處理者(Handler)
  • 1個(gè)循環(huán)器(Looper) 可綁定多個(gè)處理者(Handler)
  • 1個(gè)處理者(Handler) 只能綁定1個(gè)1個(gè)循環(huán)器(Looper)
image

Handler發(fā)送消息的兩種方式

Handler.post(Runnable r){}
Handler.sendMessage(Message msg){}

image.png

post系列方法傳入的Runnable中若持有Context的引用,會(huì)造成內(nèi)存泄漏嗎?
顯然是會(huì)的。Runnable會(huì)被封裝成Message加入到消息隊(duì)列中,只要該消息不被處理或者移除,消息隊(duì)列就會(huì)間接持有Context的強(qiáng)引用,造成內(nèi)存溢出,所以,如果該Handler是針對(duì)一個(gè)Activity的操作,在Activity的 onDestory()回調(diào)函數(shù)中中一定要調(diào)用removeCallbacksAndMessages()來防止內(nèi)存泄漏。

鏈接:

Android中為什么主線程不會(huì)因?yàn)長ooper.loop()里的死循環(huán)卡死?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容