1

Hi all may such a code cause lag of process?

while(true)
if(!connected) break;

As we see it checks for condition all the time. Would it be faster if I set small sleep in each iteration.

The code runs on Android GingerBread.

EDIT:

It waits for other Thread to finish and set variable Connected to false. Variable connected is used like lock. thread usually finds it true and waits to be false. then sets to true and only changes it at the end.

Balvonas
  • 179
  • 2
  • 11
  • 1
    What are you checking for a connection to? A lot of connections in Android have broadcasts associated with them, which would eliminate the need for such a loop entirely – Raghav Sood Feb 28 '13 at 12:47
  • 9
    If you are not connected, it is a nice way to convert your phone into a portable heater. – Alexander Pogrebnyak Feb 28 '13 at 12:48
  • 1
    @AlexanderPogrebnyak I think you are wrong. Can you explain your comment? If `connected` is `false` he will immediately `break` out of the `while` loop. – jlordo Feb 28 '13 at 12:56
  • 1
    I guess some 100 mills sleep would help save some clock cycles and battery. – Balvonas Feb 28 '13 at 13:08

3 Answers3

1

I belive it could be like this:

while(connected) {
// do stuff... 
Kajzer
  • 2,138
  • 3
  • 32
  • 46
1

I think it would be better to add small sleep in your loop, to free processor resources for other processes, especially on one-core processor.

Gunnarr
  • 101
  • 5
  • Please don't do this on Android, You will not only destroy user experience of your app but it will also leads to overall sluggish OS experience if your app is running. Do it the right way or find a right way. – M-Wajeeh Feb 28 '13 at 13:40
1

Try something like this:

private Integer connected;
private ConnectedListener connectedListener;

public interface ConnectedListener {
    public void onDisconnected();
}

private void startThreads() {
    for (int i = 0; i < 10; i++) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                synchronized (connected) {
                    connected++;
                }

                // do some random long work

                synchronized (connected) {
                    connected--;
                    if (connected == 0 && connectedListener != null) {
                        //let the listener know that we are completely disconnected
                        connectedListener.onDisconnected();
                    }
                }
            }
        }).start();
    }
}
M-Wajeeh
  • 17,204
  • 10
  • 66
  • 103