Search code examples
javaandroidhandlerlooper

Is this an example of redundant use of Handlers?


Is there any point in having multiple Handlers if they use the same Looper?

eg:

private Handler firstHandler = new Handler(Looper.getMainLooper());
private Handler secondHandler = new Handler(Looper.getMainLooper());
firstHandler.post(...);
secondHandler.post(...);

... they both post to the main thread, is that pointless to have the second one?

Thanks.


Solution

  • Is this an example of redundant use of Handlers?

    Yes.

    Quoted from the Docs:

    A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

    Those Handlers are sending messages to the same MessageQueue, so anyway the second one will run after the first one is done, meaning it's redundant.

    Further more, The Handler is associated with the Thread it's created in by default. So if the Handler is created on the main thread you don't have to specify a Looper.