Handler 源碼分析

Handler源碼的學習理解

一.相關類說明

1.Handler做用

①實現線程切換,能夠在A個線程使用B線程建立的Handler發送消息,而後在B線程的Handler handleMessage回調中接收A線程的消息。java

②實現發送延時消息 hanlder.postDelay(),sendMessageDelayed()linux

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來實現這個過程。markdown

4.Looper

經過Looper.prepare()去建立一個Looper,調用Looper.loop()去不斷輪詢MessageQueue隊列,調用MessageQueue 的next()方法直到取出Msg,而後回調msg.target.dispatchMessage(msg);實現消息的取出與分發。app

二.原理分析

咱們在MainActivity的成員變量初始化一個Handler,而後子線程經過handler post/send msg發送一個消息 ,最後咱們在主線程的Handler回調handleMessage(msg: Message)拿到咱們的消息。理解了這個從發送到接收的過程,Handler原理就掌握的差很少了。下面來分析這個過程:less

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的步驟。async

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,代碼以下:ide

//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秒)內沒法完成處理

相關文章
相關標籤/搜索