Android - Messenger vs Binder IPC

     Android's Messenger pattern is an abstraction on top of binder inter process communication to quickly implement a client-server interface. It can be used for both inter and intra process boundaries as the fundamental link is the binder driver.  Developers don't even have to deal with AIDL and instead just have to deal with an application level protocol between the interacting components and define messages. However, Messenger might not always fit the needs as,

     All messages are routed through a single thread which creates the handler for the Messenger. Although, this has the advantage of thread safety, it could also mean potential delays, especially when multiple requests could be serviced simultaneously. Besides, there is also a delay for non simultaneous requests when using Messenger.

   And, none of the requests from a client could be blocking unlike a AIDL interface api, which could either be one way or blocking. Server needs another Message to send its response. This is because of Messenger's design over binder.

IMessenger.aidl

          oneway interface IMessenger {
               void send(in Message msg);

          }

  The Message is nothing but a Parcelable which is actually sent across IMessenger binder interface as a one way transaction. The request is processed in the context of a binder thread on the server end and is relayed to the message queue of the thread which created the Messenger's handler.

Handler.java

          private final class MessengerImpl extends IMessenger.Stub {
                public void send(Message msg) {
                       Handler.this.sendMessage(msg);
                }
          }

    This relaying of the message from the binder thread to the handler thread is what causes the delay and makes all interactions as non-blocking when using Messenger pattern.
    

No comments: