I have seen the following snippet in GoogleAnalytics’ Android library code:
private class TrackerThread extends Thread {
TrackerThread() {
super("TrackerThread");
}
/**
* Simply pull Runnables from the Queue trackerQueue and call their run
* methods, blocking until there is something in the Queue.
*/
@Override
public void run() {
while (true) {
Runnable r;
try {
r = trackerQueue.take();
r.run();
} catch (InterruptedException e) {
Log.i(LOG_TAG, e.toString());
}
}
}
}
My question is, executing a Thread with a while(true) is a nice idea in a mobile environment? Will it leak the battery polling constantly or does Android have some method for optimizing that?
Thanks
As stated in the comments,
run()method of theseRunnables“blocking until there is something in the Queue”. So there is no problem with this loop: when nothing to do it will not iterate, it will be blocked.