title: Android threads with queue vs Handler/Looper: which one is efficient?
body: <p>I have a producer-consumer situation, where I want to decide between two mechanisms to implement it. It is an audio-recording/encoding case: The producer polls device microphone ,continuously, for the recorded audio, and when an audio sample is available, passes that sample to the Consumer, which is an encoder, to do the encoding and saving.</p>
  
  <p>The two available mechanisms are:</p>
  
  <ol>
  <li>Two threads with a queue to pass messages from Producer to Consumer. </li>
  <li>Or, a Handler as the consumer, where messages are posted by the producer, when it is available. </li>
  </ol>
  
  <p>But, I am not sure which one is more efficient:</p>
  
  <p>If two threads are used with a queue, then the consumer <strong>has to</strong> run in a while loop. For example, if the task continues for 5 minutes, this loop has to run for 5 minutes. While, if Handler is used, my understanding is, that the handler (consumer) only runs when there is a message, when it's handleMessage method is invoked. (Is this assumption about how handler works true, That it does not run in continues loop?). Therefore, I conclude that in this respect, handler is more efficient.</p>
  
  <p>But, on the other hand, a queue seems to be simpler mechanism, probably requiring less work, compared to Handler's message passing mechanism, which is repeated on every message (Again, is this assumption true?)</p>
  
  <p>Now, based on the above two assumptions, which to me seem conflicting, I am not sure which of the two mechanism is more efficient. </p>
  
  <p><strong>Note:</strong> I did not post any code, because, I think this a generic situation.</p>
  
  <p>Thanks.</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>In terms of implementations, both mechanisms are relatively simple to implement. My question was rather about the run-time behavior of two mechanisms. As, I have at least 5 thread where  it is critical for each of them to run continuously. Now, my question was, in such a case, which of the two options are better (Specifically for an Android application, considering how Handlers and Loopers and HandlerThread work) ?</p>
  
  <ol>
  <li>Implement N thread, each running in a while loop. Communication mechanism is simpler, a queue. But N concurrent loops.</li>
  <li>Implement producer(s) as running in a loop, but consumer(s) as Handlers. Not N concurrent loops (at least on the surface, behind the seen it might actually be the case), but a more involved communication: invoves thread message queue, Looper mechanisms, special message passing, etc.</li>
  </ol>