Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Looper vs BlockingQueue?

Can anyone explain why someone should use the Android Looper feature to create a "pipeline thread" instead of making a normal thread that pulls tasks from a BlockingQueue? On the surface, it seems like two ways to do the same thing.

like image 721
jfritz42 Avatar asked Dec 09 '11 00:12

jfritz42


People also ask

Why do we use Looper in Android?

Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare in the thread that is to run the loop, and then loop to have it process messages until the loop is stopped.

What is handler and looper in Android?

Looper is an abstraction over event loop (infinite loop which drains queue with events) and Handler is an abstraction to put/remove events into/from queue with events (which is drained by Looper) and handle these events when they are processed.

Does handler run on UI thread?

A Handler allows communicating back with UI thread from other background thread . This is useful in android as android doesn't allow other threads to communicate directly with UI thread. A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.

What is looper getMainLooper?

getMainLooper() Returns the application's main looper, which lives in the main thread of the application. MessageQueue. getQueue() Gets this looper's message queue.


1 Answers

BlockingQueue lets you have multiple consumers and producers whereas the Looper mechanism lets you have multiple producers but only one consumer.

So in Looper thread you only execute one task (runnable) at a time. The looper mechanism was created so you can easily executed runnables (tasks encapsulated as messages) on the UI thread (which runs as a single thread so think of it as a single thread consumer)

Looper/Handler also provide functionality for deferred exection of tasks which BlockingQueue out of the box doesn't. Again this is important in the context of UI toolkits.

like image 89
numan salati Avatar answered Sep 27 '22 19:09

numan salati