In my app there are few threads with while-on-volatile-boolean
loops and BlockingQueue
s for quite simple objects-messages they process (pipelined architecture).
Recently I've encountered android.os.Looper
class with it's friends, that seems to do the same job, but they are placed in API, so are there any benefits(especially performance) of using them instead of handwritten loops with explicit queues? or is it just some kind of "API sugar"?
A Looper
is just a regular Java Thread that waits until messages are posted to it. Looper
is used with the Handler
class and the Message
class. Handlers post Messages on the Looper thread. The Looper thread keeps a thread alive and loops through Messages posted by Handler.
Performance wise, there would be no advantage as far as I'm aware. It's simply keeping threads alive and posting messages to those threads. From an API point-of-view, it may be easier to use a Handler. You can create multiple Handlers that all share the same Looper. Have them post to the Looper in a thread-safe manner. There are also handy timing messages like Handler#postDelayed
. So it would just be less code to worry about.
The disadvantage is they are Android only APIs, so you are restricted to that environment.