[Android]Handlerソース解析(Java層)


前に1編の文章.と書きましたが、Androidアプリケーションのメッセージ処理メカニズムを概説しています.本稿では,この文書に基づいて,ソースレベルで展開して概説する.
単純な使用例
Handlerの使い方は以下の通りです.
Handler myHandler = new Handler() {  
          public void handleMessage(Message msg) {   
               switch (msg.what) {   
                    ...  
               }
          }   
     };

class myThread implements Runnable {   
          public void run() {  
               while (!Thread.currentThread().isInterrupted()) {    
                       
                    Message message = Message.obtain();   
                    message.what = TestHandler.GUIUPDATEIDENTIFIER;
                    TestHandler.this.myHandler.sendMessage(message);   
                    message.recycle();
                    try {   
                         Thread.sleep(100);    
                    } catch (InterruptedException e) {   
                         Thread.currentThread().interrupt();   
                    }   
               }   
          }   
     }

または、
mHandler=new Handler();
mHandler.post(new Runnable(){

    void run(){
       ...
     }
});

または、
class LooperThread extends Thread {
    public Handler mHandler;

    public void run() {
        Looper.prepare();

        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                // process incoming messages here
            }
        };

        Looper.loop();
    }
}

ソース解析
まず、構造関数を見てみましょう.
new Handler()
...
public Handler() {
    this(null, false);
}
...
public Handler(Looper looper, Callback callback) {
    this(looper, callback, false);
}
...
public Handler(Callback callback, boolean async) {
    if (FIND_POTENTIAL_LEAKS) { //    false,  true      handler      
        final Class extends Handler> klass = getClass();
        if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                (klass.getModifiers() & Modifier.STATIC) == 0) {
            Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                klass.getCanonicalName());
        }
    }
    // 1.        looper
    mLooper = Looper.myLooper();
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread that has not called Looper.prepare()");
    }
    //2.   looper  message queue
    mQueue = mLooper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}

これにより、2つのキーオブジェクトLooperとMessageQueueが導入されました.
まずmLooper = Looper.myLooper();という言葉を見てみましょう.
public static Looper myLooper() {
    return sThreadLocal.get();
}

このメソッドは、sThreadLocalオブジェクトに保存されているLooperを返します.ThreadLocalクラスについては、ここを参照してください.ここでは展開しません.現在のスレッドでLooperを実行していない場合prepare()の場合、myLooperはnullを返します.次にLooperを見てみましょうprepare()の実装:
public static void prepare() {
    prepare(true);
}

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オブジェクトを新規作成し、sThreadLocalに保存するだけであることがわかります.次にLooperのコンストラクション関数を見てみましょう.
private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

Looperを呼び出すprepare()後、Looperを呼び出す必要があります.loop()は、メッセージループを動作させることができ、そのソースコードは次のようになります.
public static void loop() {
    final Looper me = myLooper(); //1.   looper  
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    final MessageQueue queue = me.mQueue; //2.   looper   message queue

    // 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();
    // loop time.
    long tm = 0;
    ...
    for (;;) {
        Message msg = queue.next(); // 3.     message queue    
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }

        ...
        msg.target.dispatchMessage(msg); 4.   message    target handler

        ...

        // Make sure that during the course of dispatching the
        // identity of the thread wasn't corrupted.
        final long newIdent = Binder.clearCallingIdentity();
        if (ident != newIdent) {
            ...
        }

        msg.recycleUnchecked(); // 5.   message  
        ...
    }
}

Looper.を簡単にloop()は、message queueにデータがあるか否かを絶えず検出し、ある場合はコールバックを取り出して実行するデッドサイクルと理解される.次にMessageクラスを見てみましょう.
public final class Message implements Parcelable {

    public int what;

    public int arg1;

    public int arg2;

    public Object obj;

    ...

    /*package*/ int flags;

    /*package*/ long when;

    /*package*/ Bundle data;

    /*package*/ Handler target;

    /*package*/ Runnable callback;

    /*package*/ Message next;

    private static final Object sPoolSync = new Object();
    private static Message sPool;
    private static int sPoolSize = 0;
}

what,arg 1,arg 2の属性は本稿では紹介しないが,next,sPoolSync,sPool,sPoolSizeの4つの静的属性に注目する.
Messageを呼び出すとobtain()の場合、Messageオブジェクトが返されます.Messageオブジェクトの使用が完了したら、recycle()メソッドを呼び出して回収します.ここでobtainメソッドのコードは以下の通りです.
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();
}

obtainメソッドが呼び出されると、まずsPoolオブジェクトが空であるかどうかを検出し、そうでなければ新しいmessageオブジェクトとして返し、「messageオブジェクトのnext属性を指し、sPoolSizeは自滅する.messageオブジェクトはnext属性によってチェーンテーブルに直列に接続され、sPoolは「ヘッダポインタ」であることがわかる.recycleメソッドの実装を見てみましょう.
public void recycle() {
    if (isInUse()) {
        if (gCheckRecycle) {
            throw new IllegalStateException("This message cannot be recycled because it is still in use.");
        }
        return;
    }
    recycleUnchecked();
}

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 = -1;
    when = 0;
    target = null;
    callback = null;
    data = null;

    synchronized (sPoolSync) {
        if (sPoolSize < MAX_POOL_SIZE) {
            next = sPool;
            sPool = this;
            sPoolSize++;
        }
    }
}

Messageオブジェクトが使用中でない場合、回収されます.その属性はすべて元の状態に戻った後、チェーンテーブルの頭に置かれた.sPoolオブジェクトは「指向」し、sPoolSizeは自動的に増加します.
以上から,obtainメソッドとrecycleメソッドによりmessageオブジェクトを再利用できることが分かる.next、sPoolSync、sPool、sPoolSizeの4つのプロパティを操作することで、スタックのようなオブジェクトプールを実現します.
msg.targetはhandlerタイプであり、handlerメンバーのdispatchMessageメソッドにmsgパラメータが入力され、以下のように実現される.
public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

ここでは、様々なインタフェースがコールバックされていることがわかります.
これまで,メッセージキュー内のmsgオブジェクトをどのように処理するかは分かっていたが,msgオブジェクトがメッセージキュー内にどのように配置されているかはまだ分からない.通常、私たちはHandlerのsendMessage(msg)方法でメッセージを送信します.そのソースコードは以下のようになります.
public final boolean sendMessage(Message msg)
{
    return sendMessageDelayed(msg, 0);
}
...
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
...
public boolean sendMessageAtTime(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);
}
...
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

sendMessageは最終的にqueueを呼び出すことがわかる.EnqueueMessage(msg,uptimeMillis)はmsgオブジェクトをmessage queueに保存し、uptimeMillisはmsgがコールバックを実行した時刻を表す.MessageQueueクラスのenqueueMessageメソッドを見てみましょう.
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("MessageQueue", e.getMessage(), e);
            msg.recycle();
            return false;
        }

        // 1.    msg   
        msg.markInUse();
        msg.when = when;
        Message p = mMessages;
        boolean needWake;

        // 2.           (    )      when      when     when  
        if (p == null || when == 0 || when < p.when) {

            // 3.       ,        msg
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked;
        } else {
            
            //4.              :1)       2)barrier,     target 3)  msg    
            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;
                }
            }

            // 5.    msg       when      。
            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;
}

注釈と結びつけて,msg pushがqueueに到達したときのqueueの状態の変化とキューを処理する論理を知ることができる.
前述のLooperオブジェクトのloopメソッドでは、次のようになります.
for (;;) {
    ...
    Message msg = queue.next(); // 3.     message queue    
    if (msg == null) {
        // No message indicates that the message queue is quitting.
        return;
    }
    ...
    msg.target.dispatchMessage(msg); 4.   message    target handler
    
    ...
}

メッセージqueueのnextメソッドが呼び出されると、渋滞が発生する可能性があることがわかります.メッセージqueueのnextメソッドを見てみましょう.
Message next() {
    // 1.     loop       ,       mPtr
    final long ptr = mPtr;
    if (ptr == 0) {
        return null;
    }

    int pendingIdleHandlerCount = -1; // -1 only during first iteration
    int nextPollTimeoutMillis = 0;
    
    // 2.      ,        msg    。
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands(); //      ?
        }
        
        // 3.     ,nextPollTimeoutMillis      
        nativePollOnce(ptr, nextPollTimeoutMillis);

        synchronized (this) {
            // 4.      msg
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            Message msg = mMessages;
            if (msg != null && msg.target == null) {
                
                //      barrier,        asynchronous  
                do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
            if (msg != null) {
                if (now < msg.when) {
                    
                    //                   ,         ,    nextPollTimeoutMillis
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {
                    //       ,   
                    mBlocked = false;
                    if (prevMsg != null) {
                        prevMsg.next = msg.next;
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;
                    if (false) Log.v("MessageQueue", "Returning message: " + msg);
                    return msg;
                }
            } else {
                //      null
                nextPollTimeoutMillis = -1;
            }

            // Process the quit message now that all pending messages have been handled.
            if (mQuitting) {
                dispose();
                return null;
            }

            // 5.        idle(  ),   idle handle    
            //      idle    :    ;     blocking;
            if (pendingIdleHandlerCount < 0
                    && (mMessages == null || now < mMessages.when)) {
                pendingIdleHandlerCount = mIdleHandlers.size();
            }
            if (pendingIdleHandlerCount <= 0) {
                // 6.     (next   )        ,       。
                mBlocked = true;
                continue;
            }

            if (mPendingIdleHandlers == null) {
                mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
            }
            mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
        }

        //    next   ,           
        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 {
                //     true, idler   ,  next idle     。
                keep = idler.queueIdle();
            } catch (Throwable t) {
                Log.wtf("MessageQueue", "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;
    }
}

コード実行プロセスはコメントを参照してください.IdleHandlerはインタフェースです.
public static interface IdleHandler {
    boolean queueIdle();
}

IdleHandlerは、MessageQueueがidleに入ったときのhook pointを提供します.より多くの場合barrierメカニズムとともに使用され、message queueがbarrierに遭遇したときにコールバックを生成します.
まとめ
前述したいくつかの主要なクラスHandler、Looper、MessageQueue、Messageの関係は以下の通りである.
  • Handlerは、Looperをスレッドにバインドし、Looperを初期化し、対外APIを提供する責任を負う.
  • LooperはメッセージループとMessageQueueオブジェクトの操作を担当します.
  • MessageQueueは、ブロックされたキューを実現します.
  • Messageは、1つのビジネスにおけるすべてのパラメータのベクターである.

  • フレーム図は次のようになります.
                +------------------+
                |      Handler     |
                +----+--------^----+
                     |        |
               send  |        |  dispatch
                     |        |
                     v        |
                    +-----  -----+
                      |      ^
               enqueue|      | next
                      |      |
             +--------v------+----------+
             |       MessageQueue       |
             +--------+------^----------+
                      |      |
      nativePollOnce  |      |   nativeWake
                      |      |
    +-----------------v------+---------------------+
                    Lower Layer
    

    最後に、MessageQueueには4つのnativeメソッドがあることに注意してください.
    //       
    private native static long nativeInit();
    private native static void nativeDestroy(long ptr);
    //      
    private native static void nativePollOnce(long ptr, int timeoutMillis);
    private native static void nativeWake(long ptr);
    //   native    
    private native static boolean nativeIsIdling(long ptr);
    

    後続記事でご紹介します.