Android - hangdle框架

文章详细探讨了Android中的消息机制,包括Message的享元模型以减少内存抖动,Looper的循环处理和线程安全,MessageQueue的同步屏障以及IdleHandler在无消息时的处理。此外,还介绍了epoll在Looper中的作用,用于高效地处理IO事件。文章还涉及了Handler内存泄漏的可能性以及如何避免。
摘要由CSDN通过智能技术生成

在这里插入图片描述

享元模型

    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();
    }
  • 通过减少调用,来减少new Message,减少内存抖动的影响,如果new太多对象,容易导致CG次数变多,内存发生停止,从而OOM。平时开发可以借用思路,内存抖动

问题思路:

  • Looper什么时候退出
 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);
        }
    }

1、优先级队列,根据时间先后顺序排队的单链表
looper开关,轮询
2、send->messagequeue.queue
3、一个线程只有1个looper,一个线程只创建一次
4、delay :1min messageQueue -> Message - >handler -> activity

1、一个线程有几个Handler?
答:n个
2、一个线程有几个looper?如何保证?
一个,通过ThreadLocation,来创建
3、Handler内存泄漏的原因?为什么其他的内部类没有说过这个问题?
因为messageQueue获取内部类,详情见 内存泄漏文章
4、为何主线程可以new handler?如果要在子线程中new Handler要做些什么准备?
因为ActivityThread里的main调用了,APP一启动就调用了(如下代码)。
子线程启动要运行loop的prepare和loop

ActivityThread.java

  public static void main(String[] args) {
       
       ······
       
        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }


        Looper.loop();

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

5、子线程中维护的Looper,消息队列无消息的时候,处理方案是什么?有什么用?
一直等待,需要调用quitSafely,释放内存、释放线程

    private native void nativePollOnce(long ptr, int timeoutMillis);// nextPollTimeoutMillis <= 0 时,会一直等待
    private native static void nativeWake(long ptr);//唤醒队列

6、既然可以存在多个Handler,往MessageQueue中添加数据(发消息时各个Handler可能处于不同线程),那它内部是如何确保线程安全?
synchronized (this)保证安全性,
7、我们使用Message时,应该如何创建它?
答:obtain。通过享元设计模式内存共享,防止内存抖动
8、使用Handler的PostDelay后,消息队列会有什么变化?
在计算等待时间,然后进行对应的操作。
9、Looper死循环为什么不会导致应用卡死
不会。

https://blog.csdn.net/ly0724ok/article/details/117324053

HandlerThread.java

    @Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        //和getLooper的 synchronized (this) 互斥
        synchronized (this) {
        //执行完成后,唤醒getlooper里的线程
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }
    
    /**
     * This method returns the Looper associated with this thread. If this thread not been started
     * or for any reason isAlive() returns false, this method will return null. If this thread
     * has been started, this method will block until the looper has been initialized.
     * @return The looper.
     */
    public Looper getLooper() {
    //如果线程没有执行start 就会返回null 
        if (!isAlive()) {
            return null;
        }

        boolean wasInterrupted = false;

        // If the thread has been started, wait until the looper has been created.
        synchronized (this) {
        //为什么使用while 不使用if
        // 答:if只执行一次,防止有其他地方执行 notifyAll();
            while (isAlive() && mLooper == null) {
                try {
                //主线程没有执行时,等待 notifyAll();
                    wait(); notifyAll();
                } catch (InterruptedException e) {
                    wasInterrupted = true;
                }
            }
        }

        /*
         * We may need to restore the thread's interrupted flag, because it may
         * have been cleared above since we eat InterruptedExceptions
         */
        if (wasInterrupted) {
            Thread.currentThread().interrupt();
        }

        return mLooper;
    }

1、messageQueue:next 加锁为了在存消息的时候和取消息的时候互斥,创建一个native层的Looper对象

messageQueue.java

  @UnsupportedAppUsage
    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();
            }
            // epoll 的消息的循环与阻塞 负责轮询是否有消息
            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;
                //msg.target == null 判断是否有消息屏障
                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;
                }
                
                //idlehandler 最后判断执行,在没有消息轮询的时候,才会运行,用于执行不重要的信息
                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;
        }
    }



2、Message:消息在执行完之后,执行 recycleUnchecked()清空,置为0

Message.java


   @UnsupportedAppUsage
    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、looper:

/system/core/libutils/Looper.cpp
class looper {

    Looper::Looper() {
       // 重头戏:mWakeEventFd 是用来监听 MessageQueue 是否有新消息加入
        int mWakeEventFd = eventfd();
        rebuildEpollLocked();
    }

    void rebuildEpollLocked(){
        // 重头戏:在 Looper 初始化时创建了 epoll 对象
        int mEpollFd = epoll_create();
        // 把用于唤醒消息队列的eventfd 添加到 epoll 池
        epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeEventFd, & eventItem);
    }

}

epoll机制 :epoll之会把哪个流发生了怎样的I/O事件通知我们。此时我们对这些流的操作都是(复杂度降低到了O(1))有意义的。
epoll是linux内核中的一种可扩展IO事件处理机制。大量应用程序请求时能够获得较好的性能。

https://www.jianshu.com/p/0277ed66da14

looper总体调度总结:
在message初始化时就会创建一个looper,looper初始化会执行和创建epol的一些函数,然后进行监听fd的方式来形成阻塞。来消息之后就回去wakeEventFd去写一个“1”值,epoll监听到之后就回解除阻塞,继续执行。

4、消息屏障

消息屏障: 用于阻碍主线程的handler执行,让looper处于挂起状态
使用:
ViewRootImpl接收屏幕垂直同步信息事件用于驱动UI测绘,保证UI的即使刷新,不会被其他handler阻碍。消息屏障和异步消息发送是同步的。

ViewRootImpl.java

  @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
    void scheduleTraversals() {
        if (!mTraversalScheduled) {
            mTraversalScheduled = true;
            mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
            mChoreographer.postCallback(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
            notifyRendererOfFramePending();
            pokeDrawLockIfNeeded();
        }
    }

https://blog.csdn.net/my_csdnboke/article/details/109531168

5、ideleHandler

在messageQueue空闲时会执行,用于执行不太只要的一些消息,例如 Activity1 -》 Activity2 时,Activity2的onStop方法

面试

Message

代表一个行为what或者一串动作Runnable, 每一个消息在加入消息队列时,都有明确的目标。通过享元设计模式内存共享,防止内存抖动,初始化

Handler

消息的真正处理者, 具备获取消息、发送消息、处理消息、移除消息等功能

ThreadLocal

线程本地存储区(Thread Local Storage,简称为TLS),每个线程都有自己的私有的本地存储区域,不同线程之间彼此不能访问对方的TLS区域。ThreadLocal的作用是提供线程内的局部变量TLS,这种变量在线程的生命周期内起作用,每一个线程有他自己所属的值(线程隔离)

MessageQueue (C层与Java层都有实现)

以队列的形式对外提供插入和删除的工作, 其内部结构是以双向链表的形式存储消息的。核心方法是next方法,里面会有一个foir循环进行轮询
next: 先判断是否有消息屏障,有就执行异步消息,然后则执行正常的消息队列,最后当消息队列没有消息,并且空闲时,就回执行会执行ideleHandler。

Looper (C层与Java层都有实现)

Looper是循环的意思,它负责从消息队列中循环的取出消息然后把消息交给Handler处理。没有消息的时候就会挂起,有消息时则由messageQueue进行唤醒。
这里采用了epoll机制,epoll是linux内核中的一种可扩展IO事件处理机制。大量应用程序请求时能够获得较好的性能。主要有三个方法,初始化、阻塞和轮询,唤醒和获取数据
在message初始化时就会创建一个looper,looper初始化会执行和创建epoll的一些函数,然后进行监听fd的方式来形成阻塞。来消息之后就回去wakeEventFd去写一个“1”值,epoll监听到之后就回解除阻塞,继续执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值