Balvonas
Balvonas

Reputation: 189

Java code speed improvement

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.

Upvotes: 1

Views: 208

Answers (3)

M-Wajeeh
M-Wajeeh

Reputation: 17284

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();
    }
}

Upvotes: 1

Gunnarr
Gunnarr

Reputation: 101

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.

Upvotes: 1

Kajzer
Kajzer

Reputation: 2385

I belive it could be like this:

while(connected) {
// do stuff... 

Upvotes: 1

Related Questions