MessageQueue and Looper in Android


Most of you are familiar with threads in Java but Android provides one more class HandlerThread derived from Thread. The only significant difference is HandlerThread incorporates Thread, MessageQueue and Looper in it.




MessageQueue

MessageQueue is a message loop or message queue which basically contains a list of Messages or Runnables (set of executable code).
In other words MessageQueue is a queue that has tasks called messages which should be processed.
Android maintains a MessageQueue on the main thread.


Looper

Looper is a worker that serves a MessageQueue for current thread. Looper loops through message queue and sends messages to corresponding handlers to process.
Any thread can have only one unique Looper, this constraint is achieved by using a concept of ThreadLocal storage.


Benefits of Looper and MessageQueue

There are some advantages to use Looper and MessageQueue as described below-
  • ·       With the use of MessageQueue execution is sequential so in case of concurrent threads this will avoid race conditions.
  • ·       Normally thread cannot be reused once its job is completed. But thread with Looper is kept alive until you call quit method so you don't need to create a new instance each time you want to run a job in background.


To know about the handler refer below link for detail-



To find more interesting topics on Software development follow me at https://medium.com/@ankit.sinhal

You can also find my Android Applications on play store

Comments

Popular posts from this blog

Android Performance: Avoid using ENUM on Android

Android O: Impact On Running Apps And Developer Viewpoint

Smart way to update RecyclerView using DiffUtil