Search code examples
androidandroid-handlerandroid-looper

Why still calling nativeWake() when the thread not blocking?


Why still calling nativeWake() when the thread not blocking?

when a thread call the method enqueueMessage(), which means the thread is not blocking, but Why still calling nativeWake()?

MessageQueue#enqueueMessage

boolean enqueueMessage(Message msg, long when) {

       ……
            if (needWake) {
                nativeWake(mPtr);
           }
     }

Solution

  • When all messages are waiting, and you call enqueue to one of them, it's just checking the head, in case something important just installed on the top.

            //Log.d("MessageQueue", "Enqueing: " + msg);
            Message p = mMessages;
            if (p == null || when == 0 || when < p.when) {
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked; // new head, might need to wake up
            } else {
                Message prev = null;
                while (p != null && p.when <= when) {
                    prev = p;
                    p = p.next;
                }
                msg.next = prev.next;
                prev.next = msg;
                needWake = false; // still waiting on head, no need to wake up
            }
        }
        if (needWake) {
            nativeWake(mPtr);
        }
    

    So you just skipped the important part.