美文网首页
Handler工作原理

Handler工作原理

作者: 赛非斯 | 来源:发表于2021-09-28 08:59 被阅读0次

说到Handler 就不得不说Looper、 Message 、MessageQueue 、sThreadLocal、nativePollOnce、同步屏障

  • 先说说MessageQueue 顾名思义消息队列,实际上是链表结构,为什么这么说?看它消息入队的源码就知道了 msg.next = p; .
    还有一句代码比较关键 nativeWake(mPtr); 这是告诉监听的线程有消息插入了消息队列了
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;
    }
  • Message 就是我们通过Handler发送的消息,可以想象系统中每时每刻都在发消息,不会导致系统内存爆掉吗,看了源码才知道,复用机制的使用有效避免了这个问题:
    /**
     * 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;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }
  • Looper,相当于消息传递的发动机 不断从MessageQueue中取出消息 ,如果没有消息怎么办
    我们看MessageQueue的第二个核心代码 ,Looper的loop 循环中就是循环调用messagequeue的next(),为什么不会导致系统cpu消耗品殆尽,原因就在下面 ”nativePollOnce(ptr, nextPollTimeoutMillis);“ 即 传说中的epoll机制,一个文件描述符,没有消息就休眠,又消息就会被唤醒
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;
        }
    }‘
  • sThreadLocal 是个啥玩意,看下面代码 他是用来存储Looper 的,我们知道一个线程只有一个Looper,N个Handler,一个Messagequeue,所以sThreadLocal 也是唯一的。
   /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }
  • 同步屏障,大厂面试经常被问道:怎么发送一个紧急消息优先被执行(其实就是插队),通过MessageQueue的postSyncBarrier插入消息队列,这条消息的特点就是没有target ,所以看如下代码,就是要找到这个类型的消息 优先执行!!
    mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier(); //紧急消息屏障

msg.setAsynchronous(true); //异步信号

if (msg != null && msg.target == null) {遇到屏障  msg.target == null
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());遍历消息链表找到最近的一条异步消息
                }
  • sendMessageAtTime 原理是啥,它是怎么插入到消息队列的,消息队列的数据结构是个啥
   public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) {
        MessageQueue queue = mQueue;
        if (queue == null) {
            RuntimeException e = new RuntimeException(
                    this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
            return false;
        }
        return enqueueMessage(queue, msg, uptimeMillis);
    }
//调用到messagequeue的enqueueMessage
 return queue.enqueueMessage(msg, uptimeMillis);


//messagequeue 里要做的就是根据要插入的时间跟消息队列的时间对比,找到一个比上一个节点时间早比下一个时间节点晚的地方插入
            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; //Indicates whether next() is blocked waiting in pollOnce() with a non-zero timeout
            } 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;//定义一个pre指针指向 正在处理的节点
                    p = p.next; //p指向下一个节点
                    if (p == null || when < p.when) {//如果下一个节点空 或者要插入的消息比下一个节点早 break;
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next//要插入的节点放到下一个节点前面
                prev.next = msg;//要插入的节点放到当前要执行的节点后面
            }
   if (needWake) {  /./表示当前底层pollwait中需要唤醒
                nativeWake(mPtr);//底层是写1 ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd.get(), &inc, sizeof(uint64_t)));
      }
  • nativePollOnce(ptr, nextPollTimeoutMillis); 底层原理
    Looper.cpp的 int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) 方法
    看:它根据下一个消息的时间跟当前要delay的时间计算一个时间作为休眠时间
    int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
    调用epoll_wait 写入要等待的时间
    epoll_wait(mEpollFd.get(), eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
int Looper::pollInner(int timeoutMillis) {
#if DEBUG_POLL_AND_WAKE
    ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
#endif

    // Adjust the timeout based on when the next message is due.
    if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {
        nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
        int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
        if (messageTimeoutMillis >= 0
                && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {
            timeoutMillis = messageTimeoutMillis;
        }
#if DEBUG_POLL_AND_WAKE
        ALOGD("%p ~ pollOnce - next message in %" PRId64 "ns, adjusted timeout: timeoutMillis=%d",
                this, mNextMessageUptime - now, timeoutMillis);
#endif
    }

    // Poll.
    int result = POLL_WAKE;
    mResponses.clear();
    mResponseIndex = 0;

    // We are about to idle.
    mPolling = true;

    struct epoll_event eventItems[EPOLL_MAX_EVENTS];
    int eventCount = epoll_wait(mEpollFd.get(), eventItems, EPOLL_MAX_EVENTS, timeoutMillis);

相关文章

网友评论

      本文标题:Handler工作原理

      本文链接:https://www.haomeiwen.com/subject/uoehnltx.html