温习一下Handler

761 阅读12分钟
   三年,感觉就是一个坎,最近压力有点大,总是在胡思乱想,想想自己的竞争力,除了知道自己从字节快手工
   作过,剩下的就是CV操作,感觉啥都不会。特别是在这个大环境之下,感觉愈发慌乱了,想想,还是不要过于
   紧张,把之前学到的,看到的,记录一个Doc吧,总结一些。

一定要学会的

Handler我们也用了很久了,内部的逻辑我想大家也都了然了,这我在记录一下。当然,我们还是提出问题,跟着问题去分析。

  • Handler的简单实用方式和场景。
  • Hanlder的消息机制实现的大概原理。
  • 如何创建一个自己的Handler?
    • Android系统是怎么创建的?
    • HandlerThread简单原理。

详细解析

简单使用

现在我们用Handler大部分就是为了实现线程切换,发送一个消息,在主线程做一些我们预期的操作,比如更新UI等。没有很多特别需要讲解的。

Handler(Looper.getMainLooper()).post { 
  // do something
}
原理流程

发送消息

首先,我们通过Handler发送一个消息,我们分析一下。

public final boolean post(@NonNull Runnable r) {
   return  sendMessageDelayed(getPostMessage(r), 0);
}
  • 首先通过getPostMessage构建一个消息对象Message。
  • 第二个参数,就是希望当前消息的延迟执行的时间,单位毫秒,3000,就意味着希望当前的消息3s后被执行。

我们看一下,消息对象是如何构建的。

private static final int MAX_POOL_SIZE = 50;

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

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();
}
  • 会调用Message的obtain方法,获取一个消息对象。
    • 构建消息对象,这个sPool是一个缓存队列,是一个链表,维护的大小是MAX_POOL_SIZE。
    • 当我们发送消息的时候就会构建一个消息对象,这个消息对象被使用之后,会清除标记位,放到缓存队列,方便下一次使用。
    • 所以,经常建议,我们自己在构造Message对象的时候,不要new,要通过obtain方法获取。
  • 获得消息对象之后,把当前的Runnable绑定到消息对象上,方便当前消息被执行的时候,回到给到外界。

值得学习的地方:这个缓存很值得我们学习,比如RecyclerView的缓存池。为什么呢?很多人说,不就是一个缓存吗,有很大用吗?不不不,很有用。首先我们要支持哪些场景需要缓存?

如果你的使用场景,存在频繁创建对象的时候,就需要用到缓存复用的思想。如果场景比较单一,大可不必(如果追求极致,使用也不是不可以。),比如Message对象的构建,频繁发生,如果频繁的创建对象,但是没有复用。那么就会导致虚拟机频繁GC,导致内存抖动,一旦GC就会Stop the world。带来的后果也是致命的,可能给用户直接的感受,就是卡顿,所以这点在性能优化上也很重要。

public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

这个时候,获取系统开机时间,加上延迟执行的时间,就是预期消息执行的时间。很好理解。

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

这里需要注意的是,mAsynchronous,如果这个值是true,就意味着,当前handler发送的消息都是异步消息,默认都是同步消息。这个和同步屏障有关,不要被名字迷惑了,很简单,后面说。

  • 当前消息的target是当前的handler,持有一个引用
    • 这个也就是一些内存泄露的原因,handler持有activity,Message持有handler,messagQueue持有message,MessageQueue主线程一直存在运行,导致Activity泄露。
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;
}

这个就是具体的,消息入队列的行为,Java层的行为。

  • 首先判断mQuitting,如果当前消息循环关闭了,直接返回false。
  • 没有很复杂,很好懂,就是拿到当前msg的预期执行时间,并且插到消息链表中,消息链表是根据时间先后排列的。
  • needWake,需要唤醒消息循环
    • 如果当前消息队列是空的,当前插入了一条消息,成为了头结点,需要把阻塞的消息轮询唤醒。很好理解,没有消息的时候,这个时候就会处于阻塞休眠状态,有了新的消息加入,如果阻塞就需要唤醒。
    • 如果当前消息是最早的异步消息并且预期执行时间靠前,并且消息头结点是消息屏障,也需要换新阻塞状态的消息轮询。同样的,如果有消息屏障,会拦截同步消息,只会处理了异步消息。如果这个时候来了新的优先级更高的异步消息,就需要把阻塞态唤醒,如果优先级不高,前面的异步消息都在休眠,你着急个啥嘛,哈哈哈
处理消息
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));
}

首先是准备Looper,这个只能初始化一次,并且是ThreadLocal的,Looper适合线程绑定的,也就是说,是线程安全的,这个也是通过Handler实现线程切换的重要的一环。

public static void loop() {
    final Looper me = myLooper();
    ......

    for (;;) {
        Message msg = queue.next(); // might block
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }
      ......
        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);
            }
        }
        ......

        msg.recycleUnchecked();
    }
}

这个也很好理解,通过消息队列MessageQueue获取消息,执行这个消息,并回收这个消息对象。

  • 首先通过next()方法,去一个消息出来。
  • msg.target.dispatchMessage(msg),每一个消息持有一个handler的引用,回调给handler,去处理这个事件。
  • msg.recycleUnchecked(),把这个消息重置,放到sPool缓存,方便下次使用。
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;
    }
}

这个就是消息的具体轮询操作,依旧是一个死循环,知道有消息返回,否则我们就休眠,我们一起看看。

  • nativePollOnce(ptr, nextPollTimeoutMillis) 这个方法是调用Native方法,休眠用的。我们之前说过,每一个Msg都有一个预期执行的时间,如果当前一个消息也没有获取到,也不会直接退出循环,会直接循环。具体的大家可以了解一下Epoll(现在面试也问,真他妈卷。)
  • msg != null && msg.target == null,如果存在消息屏障,直接遍历message链表,找到异步消息,直接返回。
  • 否则,就直接遍历链表,找到第一个节点(第一个节点预期执行时间最早),如果该执行了就直接返回,如果时间没找到,就阻塞等待。
  • 如果还是没有找到消息msg对象,这个时候,就找到IdleHandler执行。
    • IdleHandler,之前我来快手面过,我还不知道是啥?哈哈哈,这个IdleHandler就是等待没有消息执行,空闲的时候,执行。
    • IdleHandler,通过不同的返回值,可以执行一次移除,还可以常驻,空闲就会重新执行一次。(我工作中目前没有用过,我们可以自行看看系统中哪些用到IdleHandler)。
什么是消息屏障

我之前第一次听说这个名词,也感觉很蒙,啥玩意儿,这么高深吗?难道有什么黑科技?其实不是,我们的消息执行,消息其实是一系列的Message,这些Message都有一个时间戳,标识当前要执行的时间。但是如果来了一条紧急的消息怎么办呢?是的,屏障的作用就体现了。

private int postSyncBarrier(long when) {
    // Enqueue a new sync barrier token.
    // We don't need to wake the queue because the purpose of a barrier is to stall it.
    synchronized (this) {
        final int token = mNextBarrierToken++;
        final Message msg = Message.obtain();
        msg.markInUse();
        msg.when = when;
        msg.arg1 = token;

        Message prev = null;
        Message p = mMessages;
        if (when != 0) {
            while (p != null && p.when <= when) {
                prev = p;
                p = p.next;
            }
        }
        if (prev != null) { // invariant: p == prev.next
            msg.next = p;
            prev.next = msg;
        } else {
            msg.next = p;
            mMessages = msg;
        }
        return token;
    }
}

一般我们构建Handler的实收或者创建Message对象的时候,传递asyncChronous=true,设置屏障消息。这里是MessageQueue设置消息屏障。

  • 首先构造一个消息对象,设置特殊的标记位置。handler=null,回顾之前,我们发送消息的时候,都会把消息打上一个handler的引用,标识这个Msg是由哪一个handler发出来的。这里不需要,屏障消息不需要给handler反馈,就是充当消息队列的一个标识。
  • 遍历消息队列,消息队列是根据执行时间从前到后排列的。屏障消息也是一样的,根据when插入到消息链表之中。
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());
}

在MessageQueue的next()方法获取消息的时候,如果当前存在消息屏障(msg.handler==null),这个时候,就获取消息屏障之后的异步消息(asyncChronous=true),忽略同步消息。(消息屏障在使用完毕之后,记得及时移除,否则屏障后面的同步消息就会得不到执行。)

所以消息屏障的目的就是优先处理异步消息,在Android绘制的时候,scheduleTraversals也是会发送一个这样的消息,目的就是保证绘制优先执行,UI尽可能快速的展示,防止画面出现卡顿。

自己的Handler

Handler不是主线程特有的,任何一个线程都可以有一个自己的Handler,实现自己的消息队列,具体的方式如下。

使用流程
val threadWithLooper = object : Thread() {

  var threadLooper: Looper? = null

  override fun run() {
    Looper.prepare()
    threadLooper = Looper.myLooper()
    Looper.loop()
    
  }
}
  • 首先我们构建一个Thread,然后在run方法(线程启动的时候),启动消息循环
    • 首先prepare,通过ThreadLocal构建一个Looper对象。(如果有人关心MessageQueue,这个也是在Looper初始化一起创建创建的,Looper适合MessageQueue绑定的,一比一的)。
    • 然后把Looper取出来保存成局部变量。

这样会有什么问题吗?是的,并发问题。这是一个异步线程,如果你在主线程或者其他线程,要创建Handler,去获取ThreadWithLooper的Looper,这个时候Looper可能还没有创建好,出现问题,我们就不得不在获取Looper加锁了。那么有么有好的方式呢?是的,HandlerThread。我们一起看看。

HandlerThread
@Override
public void run() {
    mTid = Process.myTid();
    Looper.prepare();
    synchronized (this) {
        mLooper = Looper.myLooper();
        notifyAll();
    }
    Process.setThreadPriority(mPriority);
    onLooperPrepared();
    Looper.loop();
    mTid = -1;
}

public Looper getLooper() {
    if (!isAlive()) {
        return null;
    }
    
    // If the thread has been started, wait until the looper has been created.
    synchronized (this) {
        while (isAlive() && mLooper == null) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }
    }
    return mLooper;
}

为了保证安全,一定可以获得Looper,做了如下:

  • 首先,在获取getLooper的时候,如果获取不到(looper是null),这个时候就wait阻塞,while循环,直到looper成功赋值。
  • 在run方法的时候,给mLooper赋值,赋值成功之后,调用notifyAll,唤醒那些为了获取Looper,处于wait状态的线程。
系统是怎么创建的?

我们知道App的入口,其实就是ActivityThread,从main函数入口的。当应用点开,进程创建,就会反射创建ActivityThread,就开始构建消息的循环。

public static void main(String[] args) {
    ......

    Looper.prepareMainLooper();

    ......
    Looper.loop();

    throw new RuntimeException("Main thread loop unexpectedly exited");
}

没有什么区别,也是先准备Looper,然后让消息队列循环起来。会不会有人问,为啥没有和HandlerThread一样,加锁,wait,以及notifyAll?我个人理解,因为这个是进程创建,刚开始的时候会就反射执行main方法,准备Looper,这个时候视图也没有创建,也不会有什么需求用到Handler去进行线程切换,去执行一些任务非要在主线程,应该是有依赖顺序的。

总结

Handler我们可以学到的,总结一下:

  • handler,looper,queue之间的关系,分别是处理消息,获取消息,存消息,按照时间先后执行。
    • 他们之间的数量关系,N:1:1的,handler是一个发送和处理的媒介,实现线程的切换。后面两者才是消息转起来的核心。
    • 知道IdleHandler是什么东西,实现空闲调用。
    • 知道常见内存泄露怎么引起的,怎么解决。
  • HandlerThread的出现
    • 可以异步调用,处理一些稍中的任务,不阻塞UI线程。当然和线程池比起来还是有不足,毕竟单线程的。
    • 简化实现消息机制实现,解决并发打来的looper没有准备好的问题。

扩展学习:

  • 学习缓存队列,MSG的复用。
    • 这个很有用,别面对象大量创建,频繁GC。