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秒)内没法完成处理

相关文章
相关标签/搜索