Polling

Avoid using loops that poll. The following is a snippet of code that polls the keepRunning flag. (printText(String) just displays String in a UI component.)

boolean keepRunning = false;

public void run(){

printText("Started"); while(keepRunning){

printText("In loop");

printText("Stopped");

Running the loop increased battery consumption from 66 mA to an unacceptable 163mA on my Psion Series 5MX (unfortunately there is no easy way of monitoring battery consumption on more recent mobile phones). The battery consumption returned to 66 mA when keepRunning was set to false. Further, loops like this will hog the CPU and deprive other applications of CPU cycles.

In order to read from an InputStream we can sit in a loop polling for the number of available bytes using InputSteam.available(). When data becomes available, we read it using InputStream.read(). However, it is far better to create a separate reader thread that calls InputStream.read() directly. Because this method blocks, the thread will wait until data is present and not consume any unnecessary CPU bandwidth. Although both an event model and a wait-notify model require an extra Thread, this is generally worthwhile.

0 0

Post a comment

  • Receive news updates via email from this site