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.
The two available mechanisms are:
- Two threads with a queue to pass messages from Producer to Consumer.
- Or, a Handler as the consumer, where messages are posted by the producer, when it is available.
But, I am not sure which one is more efficient:
If two threads are used with a queue, then the consumer has to 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.
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?)
Now, based on the above two assumptions, which to me seem conflicting, I am not sure which of the two mechanism is more efficient.
Note: I did not post any code, because, I think this a generic situation.
Thanks.
Edit:
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) ?
- Implement N thread, each running in a while loop. Communication mechanism is simpler, a queue. But N concurrent loops.
- 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.