Android Message.obtain() 之 高效原因分析

当在学习跨线程机制 Handler 时,一定会接触到 Message.obtain() 方法

当在学习Message.obtain 时,可能有几个疑问:

  1. Message的集合的具体存储结构是怎样的?
  2. 两种Message构建方法:Message.obtain() 和 new Message() 之间的区别?
  3. Message.obtain() 调用后获取的链表节点缓存对象会不会形成脏数据?
  4. new Handler().obtainMessage() 和 Message.obtain() 区别?

弄清这几个问题的方式还是从源码入手比较干脆:

问题1:Message的集合的具体存储结构是怎样的?

先抛结论:单链表(MAX_POOL_SIZE = 50)

  • 第1段关键代码位于 Handler.java

在Client调用new Handler().postDelayed()等方法后,沿着调用链,会调用到Handler类关键方法enqueueMessage(),把Message塞入MessageQueue

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
  • 第2段关键代码位于 MessageQueue.java

MessageQueue虽命名为Queue(队列),但从源码和Message角度看出,调用MessageQueue postSyncBarrierenqueueMessage等方法时,逻辑结构是线性表,存储结构是链表而不是队列;但从注册的回调监听 - mIdleHandlers看,倒是符合队列性质;我们姑且叫它为队列吧

在enqueueMessage中调整消息顺序:
新插入消息(节点=msg)的后继指针(指针=msg.next)指向当前消息(节点=mMessages) - msg.next = p;
当前消息指针(指针=mMessages)指向新插入的消息(节点=msg) - prev.next = msg;

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

问题2:两种Message构建方法:Message.obtain() 和 new Message() 之间的区别?

先抛结论:Message.obtain() 比 new Message() 更高效

关键代码:位于 Message.java

调用obtain方法后,优先查找Message单链表表头是否已有Message对象,有则利用,无则创建;所以Message.obtain() 和 new Message() 之间的区别:Message.obtain()更高效,因为节省了为Message分配、创建、调整内存的操作

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

问题3:Message.obtain() 调用后获取的链表节点缓存对象会不会形成脏数据?

先抛结论:不会

关键代码位于:Looper.java

由问题2知,Message.obtain是取缓存操作,Message会持有what、when等变量,如果我们重用表头的Message,岂不是取到了脏数据?

Android SDK当然会解决这个问题:Looper机制,Android的Looper机制原理和设计思想 可类比 iOS中的Runloop,开启一条线程,同时开启一个消息循环,制造一个常驻线程
只是Runloop的业务场景更底层些(内核所启动的消息循环,控制内核态和用户态切换)

loop()方法实现的最后一行msg.recycleUnchecked()正解决了问题3,每一次loop结尾,Android SDK都会帮我们把执行完毕的消息所持有的变量重置到初值,以使下次使用时保证数据整洁

/**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    public static void loop() {
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;

        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        // Allow overriding a threshold with a system prop. e.g.
        // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
        final int thresholdOverride =
                SystemProperties.getInt("log.looper."
                        + Process.myUid() + "."
                        + Thread.currentThread().getName()
                        + ".slow", 0);

        boolean slowDeliveryDetected = false;

        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            // This must be in a local variable, in case a UI event sets the logger
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long traceTag = me.mTraceTag;
            long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
            long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
            if (thresholdOverride > 0) {
                slowDispatchThresholdMs = thresholdOverride;
                slowDeliveryThresholdMs = thresholdOverride;
            }
            final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
            final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

            final boolean needStartTime = logSlowDelivery || logSlowDispatch;
            final boolean needEndTime = logSlowDispatch;

            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }

            final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
            final long dispatchEnd;
            try {
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (logSlowDelivery) {
                if (slowDeliveryDetected) {
                    if ((dispatchStart - msg.when) <= 10) {
                        Slog.w(TAG, "Drained");
                        slowDeliveryDetected = false;
                    }
                } else {
                    if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                            msg)) {
                        // Once we write a slow delivery log, suppress until the queue drains.
                        slowDeliveryDetected = true;
                    }
                }
            }
            if (logSlowDispatch) {
                showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
            }

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            // Make sure that during the course of dispatching the
            // identity of the thread wasn't corrupted.
            final long newIdent = Binder.clearCallingIdentity();
            if (ident != newIdent) {
                Log.wtf(TAG, "Thread identity changed from 0x"
                        + Long.toHexString(ident) + " to 0x"
                        + Long.toHexString(newIdent) + " while dispatching to "
                        + msg.target.getClass().getName() + " "
                        + msg.callback + " what=" + msg.what);
            }

            msg.recycleUnchecked();
        }
    }

问题4. new Handler().obtainMessage() 和 Message.obtain() 区别

先抛结论:没有区别

关键代码位于 Handler.java

public final Message obtainMessage()
    {
        return Message.obtain(this);
    }

你可能感兴趣的:(Android Message.obtain() 之 高效原因分析)