深挖Handler机制

一.PriorityQueue优先级队列

在讲Handler之前,先讲一下优先级队列,在Java中具体呈现的类是PriorityQueue,其实现了Queue接口,延展一下Java的集合


Queue以及Deque都是继承于Collection,Deque是Queue的子接口。Deque是double ended queue,我将其理解成双端结束的队列,双端队列,可以在首尾插入或删除元素。而Queue的解释中,Queue就是简单的FIFO队列。所以在概念上来说,Queue是FIFO的单端队列,Deque是双端队列。
PriorityQueue类,Java给出的解释如下:

它是基于优先级堆的无边界(这里讲的无边界的含义是指可自动扩容集合长度)优先级队列,优先级队列中众多元素的排列,要么基于它天然的排序性(即实现Comparable接口的类,若插入的类未实现该接口会报类型转换错误),要么就是基于在构造函数传入的Comparator比较器
offer进栈源码如下:

transient Object[] queue;
public boolean offer(E e) {
        if (e == null)
            throw new NullPointerException();
        modCount++;
        int i = size;
        if (i >= queue.length)
            grow(i + 1);
        size = i + 1;
        if (i == 0)
            queue[0] = e;
        else
            siftUp(i, e);
        return true;
    }

    private void siftUp(int k, E x) {
        if (comparator != null)
            siftUpUsingComparator(k, x);
        else
            siftUpComparable(k, x);
    }

    private void siftUpComparable(int k, E x) {
        Comparable key = (Comparable) x;
        while (k > 0) {
            int parent = (k - 1) >>> 1;
            Object e = queue[parent];
            if (key.compareTo((E) e) >= 0)
                break;
            queue[k] = e;
            k = parent;
        }
        queue[k] = key;
    }

    private void siftUpUsingComparator(int k, E x) {
        while (k > 0) {
            int parent = (k - 1) >>> 1;
            Object e = queue[parent];
            if (comparator.compare(x, (E) e) >= 0)
                break;
            queue[k] = e;
            k = parent;
        }
        queue[k] = x;
    }

大概如下:优先级队列内部用数组实现,在插入元素时,会先扩容数组大小加1,然后通过排序方法将该元素插入指定位置中
poll出栈源码如下:

public E poll() {
        if (size == 0)
            return null;
        int s = --size;
        modCount++;
        E result = (E) queue[0];
        E x = (E) queue[s];
        queue[s] = null;
        if (s != 0)
            siftDown(0, x);
        return result;
    }

出栈既是将数组第一个元素删除,但这里不会讲数组大小减1,而且将数组最后一个位置置为null,并将数组1-size-1的所有元素前置1位。
以上就是优先级队列的概念

二.Handler机制

  • Handler:用来发送消息:sendMessage等多个方法,并实现handleMessage()方法处理回调(还可以使用Message或Handler的Callback进行回调处理)。
  • Message:消息实体,发送的消息即为Message类型。
  • MessageQueue:消息队列,用于存储消息。发送消息时,消息入队列,然后Looper会从这个MessageQueen取出消息进行处理。
  • Looper:与线程绑定,不仅仅局限于主线程,绑定的线程用来处理消息。loop()方法是一个死循环,一直从MessageQueen里取出消息进行处理。

Handler机制本身就是基于生产者与消费者模型,发送消息的线程是生产者,处理消息的线程是消费者(即send/post是生产线程,handleMessage的是消费线程)。其工作流程如下:

image.png

Handler有各类的send方法,和post方法,其最终都会执行MessageQueue类中enqueueMessage()方法,在入栈这些消息执行,消息本身会有处理时间即when属性,比如sendMessage(msg)方法的Message的when是系统当前时间,sendMessageDelayed方法的when是系统当前时间加上延迟时间;随后将Message入栈到MessageQueue,就是基于优先级队列的概念,会按照Message的when属性进行排序,最近的Message在前面,最晚的Message在后面。
Handler类中post一个线程其实就是send一个Message,callback属性就是该线程

private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

MessageQueue类中enqueueMessage方法源码如下:

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;
    }

这边Handler将Message置于MessageQueue中,那边Looper的loop方法正在不停从MessageQueue中消费Message,Loop类中loop方法源码如下:
Loop类:

public static void loop() {
  final MessageQueue queue = me.mQueue;
  for (;;) {
      .................
      Message msg = queue.next();
      .................
      try {
          msg.target.dispatchMessage(msg);
          dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
      } finally {
          if (traceTag != 0) {
              Trace.traceEnd(traceTag);
          }
       }
      .................
  }
}

MessageQueue类:

    Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        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;
                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;
                }

                // 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)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    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 {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    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;
        }
    }

以上源码可知,loop会不断的问MessageQueue中是否有可处理的Message,判断可处理的依据是系统当前时间是否大于等于Message的when属性,如果符合现将此message在MessageQueue队列中移除,之后return回去。如果不符合则阻塞线程,调用nativePollOnce方法,阻塞时间为nextPollTimeoutMillis;当loop有处理的message时,就会交给Handler进行dispatch分发消息

Hander中Looper相关


Looper的获取是通过ThreadLocal的get操作,其set操作是在Looper的prepare方法中,会实例化一个Looper,并将此对象存储在ThreadLocal中(由此可以看出looper的prepare方法只做looper对象的线程存储操作)

private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

一个线程可以有N个Handler,但是只有一个Looper,如何保证Looper的唯一性,就是通过ThreadLocal,其使用使用很简单,如下

static final ThreadLocal sThreadLocal = new ThreadLocal();
sThreadLocal.set()
sThreadLocal.get()

其中set,get源码如下:

public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
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();
    }

由源码可知,ThreadLocal本身实现很简单,是由ThreadLocalMap这么一个键值对Map来实现当前线程内存储变量的能力。有set源码可知,Looper的实例对象会存储在ThreadLocalMap中,其键为ThreadLocal对象本身;而ThreadLocalMap的获取是通过getMap方法,getMap方法源码如下:

ThreadLocal类:
ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}

void createMap(Thread t, T firstValue) {
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}
Thread类:
public class Thread implements Runnable {
     ThreadLocal.ThreadLocalMap threadLocals = null;
}

由ThreadLocalMap相关源码可知,ThreadLocalMap类的对象threadLocals是单个线程唯一的,looper的获取是基于threadLocal的,所以Looper是单个线程唯一的。

我们平时用的实例化的Handler都是基于主线程的,子线程如何实例化Handler呢?
要注意的几点如下:

  • Looper.prepare (实例化Looper,并存储至ThreadLocal中)
  • Looper.loop (启动for循环)
  • Looper.quit (停止loop的for循环,释放线程、释放内存)
public class HandlerDemoThread extends Thread {

    private Looper mLooper;

    @Override
    public void run() {
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
        }
        Looper.loop();
    }

    public Looper getLooper() throws Exception {
        if (!isAlive()) {
            throw new Exception("current thread is not alive");
        }
        if (mLooper == null) {
            throw new Exception("current thread is not start");
        }
        return mLooper;
    }
}

class MainActivity : AppCompatActivity() {
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val handlerThread = HandlerDemoThread()
        handlerThread.start()
        val handler1 = object : Handler(handlerThread.getLooper()) {
            override fun handleMessage(msg: Message?) {
                super.handleMessage(msg)
            }
        }

        handler1.sendMessage(Message.obtain())
    }

   override fun onDestroy() {
        super.onDestroy()
        handler1.looper.quit()
    }
   
}

由上述Handler系统源码可知,handler在初始化前,要确保当前线程prepare过,即实例化Looper存储与ThreadLocal中。还要启动Looper的loop方法,让传输带运转起来。这里有一点需要注意,由于send##,pos##方法可能会执行在不同线程中,在send一个delay消息时,由于在enqueueMessage时,会加同步锁,这样会导致delay算出来的时间是不准确的;在这里大家还要注意到,平时实例化主线程的Handler的时候,是不需要调用当前主线程的prepare与loop方法,这是因为ActivityThread已经启动过主线程的Looper。

ActivityThread就是我们常说的主线程或UI线程,ActivityThread的main方法是整个APP的入口,
ActivityThread的main方法源码如下:

    public static void main(String[] args) {
        ...
        Looper.prepareMainLooper();
        ActivityThread thread = new ActivityThread();
        //在attach方法中会完成Application对象的初始化,然后调用Application的onCreate()方法
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        ...
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

为何主线程不用调用quit方法,当然逻辑就是不行的,主线程关了,那app就关闭了。而且在quit方法中,即最终调用的是MessageQueue的quit方法,已经做了验证,源码如下:

 void quit(boolean safe) {
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }

        synchronized (this) {
            if (mQuitting) {
                return;
            }
            mQuitting = true;

            if (safe) {
                removeAllFutureMessagesLocked();
            } else {
                removeAllMessagesLocked();
            }

            // We can assume mPtr != 0 because mQuitting was previously false.
            nativeWake(mPtr);
        }
    }

private void removeAllMessagesLocked() {
        Message p = mMessages;
        while (p != null) {
            Message n = p.next;
            p.recycleUnchecked();
            p = n;
        }
        mMessages = null;
    }

    private void removeAllFutureMessagesLocked() {
        final long now = SystemClock.uptimeMillis();
        Message p = mMessages;
        if (p != null) {
            if (p.when > now) {
                removeAllMessagesLocked();
            } else {
                Message n;
                for (;;) {
                    n = p.next;
                    if (n == null) {
                        return;
                    }
                    if (n.when > now) {
                        break;
                    }
                    p = n;
                }
                p.next = null;
                do {
                    p = n;
                    n = p.next;
                    p.recycleUnchecked();
                } while (n != null);
            }
        }
    }

Message类:

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 = -1;
        when = 0;
        target = null;
        callback = null;
        data = null;

        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }

MessageQueue的quit方法,源码可知是释放掉消息队列的所有Message,以及释放Message内部参数,即释放内存。同时将全局变量mQuitting置为true,通过nativeWake再唤醒线程,由于Looper中loop不停在调用MessageQueue类的next方法,其中next方法部分源码如下:

.................
for (;;) {
      .................
      nativePollOnce(ptr, nextPollTimeoutMillis);
      synchronized (this) {
            .................
            if (mQuitting) {
                    dispose();
                    return null;
                }
           .................
      }
}

由于MessageQueue的quit已唤醒线程,所以next会一直往下走,遇到mQuitting为true,变回diapose,同时返回null,loop那边拿到null后,变回直接return loop方法。loop方法便会结束,整个线程便会得要释放。所以回到quit方法,所以quit既能释放内存,也释放了线程;

在子线程中,如果手动为其创建了Looper,那么在所有的事情完成以后应该调用quit方法来终止消息循环,否则这个子线程就会一直处于等待(阻塞)状态,而如果退出Looper以后,这个线程就会立刻(执行所有方法并)终止,因此建议不需要的时候终止Looper。即调用quit方法

这里要注意的一点是,recycleUnchecked方法中,有这么一段代码:

synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }

这里的逻辑是:从队尾将该已被内部清空,外部去除关联的Message,添加至消息池里。消息池就是用户创建Message的内存池。那Handler中如何创建消息呢?为了防止频繁实例化Message,从而引发内存抖动,这里就用到内存共享,即内存复用的概念。即调用Message中obtain方法,来获取Message实例,obtain方法源码如下:

    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();
    }

思考:为什么Handler不会阻塞主线程?

从以上分析可知,Handler在处理消息时,对于未到处理时间的队头Message,便会休眠掉进栈的当前线程,直到休眠时间结束,才会去处理队头Message。既然会休眠线程,为什么Handler没有阻塞主线程呢?

对于线程即是一段可执行的代码,当可执行代码执行完成后,线程生命周期便该终止了,线程退出。而对于主线程,我们是绝不希望会被运行一段时间,自己就退出,那么如何保证能一直存活呢?简单做法就是可执行代码是能一直执行下去的,死循环便能保证不会被退出(eg:binder线程也是采用死循环的方法,通过循环方式不同与Binder驱动进行读写操作),当然并非简单地死循环,无消息时会休眠。但这里可能又引发了另一个问题,既然是死循环又如何去处理其他事务呢?通过创建新线程的方式。真正会卡死主线程的操作是在回调方法onCreate/onStart/onResume等操作时间过长,会导致掉帧,甚至发生ANR,looper.loop本身不会导致应用卡死。

这里便会再度引发一个:主线程的死循环一直运行是不是特别消耗CPU资源呢?

当然不会,MessageQueue没有消息时,便阻塞在loop的queue.next()中的nativePollOnce()方法里,此时主线程会释放CPU资源进入休眠状态,直到下个消息到达或者有事务发生,通过往pipe管道写端写入数据来唤醒主线程工作。这里采用的epoll机制,是一种IO多路复用机制,可以同时监控多个描述符,当某个描述符就绪(读或写就绪),则立刻通知相应程序进行读或写操作,本质同步I/O,即读写是阻塞的。 所以说,主线程大多数时候都是处于休眠状态,并不会消耗大量CPU资源。

你可能感兴趣的:(深挖Handler机制)