Handler原理

Handler 原理

一、Handler消息发送机制

1. 发送消息

1.1 添加消息

调用Handler.sendMessageXX方法发送消息,这些方法最终都会调到MessageQueueenqueueMessage方法中,MessageQueue使用一个优先队列来保存添加的Message对象,执行时间越早的Message放的越靠近队头。

//加入新的头结点
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;
    //遍历链表,把最快执行的msg放到表头
    for (;;) {
        prev = p;
        p = p.next;
        if (p == null || when < p.when) {
            break;
        }
        if (needWake && p.isAsynchronous()) {
            needWake = false;
        }
    }
    //插入新的Message节点
    msg.next = p; // invariant: p == prev.next
    prev.next = msg;
}

这样就把一个Message加入到了MessageQueue中。下面要看的就是怎么样取出消息。

1.2 取出消息

Looper.loop()方法中通过一个死循环来不断的从MessageQueue中取出Message

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

MessageQueue方法中也有一个for循环来从优先队列中找出一个符合条件的Message

  • 由于MessageQueue中保存的Message是按有限顺序排列的所以第一个一定是最先执行的,先取出第一个,然后判断这个Message是否可以开始处理,

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

    如果不可以,计算还差多少时间可以处理这个Message,并把计算的时间赋值给nextPollTimeoutMillis,这样当循环到下一次的时候就会调用nativePollOnce这个方法来使本线程休眠,当休眠时间到了之后就重新取出一个Message然后返回,这样,MessageQueue.next方法就执行结束,loop方法就能拿到一个新的Message.

  • Loop方法拿到Message之后判断是否为空,如果是那loop方法死循环就结束,相当于Looper就停止工作。

    如果不为空就调用Message.target.dispatchMessage方法。在loop方法拿Message的过程中可能会因为MessageQueue的休眠而导致卡主

  • Message.target是一个Hander的引用,msg.target = this;HandlerenqueueMessage中会将当前Handler设置为Message.target的引用。所以这个方法最终也就是调用Handler.dispatchMessage方法,

    public void dispatchMessage(@NonNull Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }
    

    这个方法最终会调到handleMessage方法中,也就是在创建Handler实例时重写的那个方法。这样就能处理到这个Message

[图片上传失败...(image-1acb02-1593160818812)]

二、Looper与线程的数量关系

结论:每条线程只有一个Looper

static final ThreadLocal sThreadLocal = new ThreadLocal();

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中维护了一个ThreadLoacal的静态变量,当调用这个Looperprepare方法时会先判断当前的线程是否有一个Looper的实例,如果没有就创建一个。

public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}

ThreadLocal维护了一个类似于HashMap的数据结构用线程号作为Key,这样就保证了每条线程只会有一个对应的实例。

所以,Looper是通过ThreadLocal来保证每条线程只有一个Looper实例。如果在同一个线程中多次调用prepare方法就会抛出异常。

三、Handler内存泄露

在实例化Handler时使用匿名内部类来重写handleMessage方法,这个Handler实例就持有了外部类的引用(通常会是一个Activity),在sendMessage时又会使Message引用当前Handler实例,这样Message就会最终引用到Activity实例。由于Handler发送的消息存在延时机制导致线程可能休眠,这样休眠线程中的Message就会一直持有Activity的引用。并且在prepareThreadLocal会持有创建的Looper实例的引用,而静态的ThreadLocal又会被Looper.class持有引用。Looper.class是一个GCRoot所以在可达性分析时就不会释放Activity

[图片上传失败...(image-170ef4-1593160818812)]

四、Handler的使用

1. 主线程上Handler的使用

Looper源码中可以看到需用调用loop方法才能才能从MessageQueue中的取出消息并处理,但是在Activity中使用Handler时,我们并不需要去手动的prepare来调用loop方法。因为在Activity在启动的时候已经由Android自动prepareMainLooper

ActivityThread.main()中已经调用了Looper.prepareMainLooper方法,这个main方法时整个应用启动的入口方法,所以在这个时候就会init主线程中的Looper

2. 在子线程使用Looper

  • prepare()先调用prepare方法来在本线程创建一个Looper实例,
  • loop(),调用loop方法来从MessageQueue中取出数据
  • quit()/quitSafty()清空MessageQueue退出``Looper

五、多个线程往MessageQueue中发消息如何保证线程安全

使用synchronized关键字对enqueueMessagenext加上当前MessageQueue的锁,这样在多个线程中操作这个MessageQueue时就能保证每次只有一个线程能执行。所以发送Message的delay时间由于等待锁的原因不一定是精确的。

六、如何创建一个Message

通过Message.obtain()方法来获取一个对象。Message中维护了一个Message对象的实例链表,当调用obtain方法时就从链表中取出一个Message实例,并将这个Message的标志位重置。然后返回这个Message实例。当使用完一个Message之后会调用recycleUnCheck()方法来重置这个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 = UID_NONE;
    workSourceUid = UID_NONE;
    when = 0;
    target = null;
    callback = null;
    data = null;

    //最大保存50个
    synchronized (sPoolSync) {
        if (sPoolSize < 50) {
            next = sPool;
            sPool = this;
            sPoolSize++;
        }
    }
}

七 、quit和quitSafty的区别

1. quit

这个方法直接移除MessageQueue中所有的Message并将其重置。

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

2. quitSafty

这个不会移除当前已经到达执行时间的Message,会让让其正常处理完成,只会移除没有到达处理时间的Message

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) {
                    //n节点及之后的节点都还不到执行的时间
                    break;
                }
                p = n;
            }
            p.next = null;
            //将还不到执行时间的message全部移除
            do {
                p = n;
                n = p.next;
                //把target置为null
                p.recycleUnchecked();
            } while (n != null);
        }
    }
}

在执行着两个方法之后会调用nativeWake(mPtr)来唤醒在休眠的next方法,这个方法如果返回一个空的messageLooper就会推出循环。

[图片上传失败...(image-3daee6-1593160818812)]

你可能感兴趣的:(Handler原理)