Is busy wait inconsistent?

183 views Asked by At

I want a busy wait loop for a specific amount of time and I tested the following java code, which gives different outputs on different runs (sometimes). Most of the time it gives 16 and 0. It means one can not trust a busy wait. What is the reason?

public class Testme {

    public Testme() {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10000000L; i++) {}

        long end = System.currentTimeMillis();

        System.out.println(end - start);
    }

    public static void main(String[] args) {
        new Testme();
    }
}
2

There are 2 answers

0
Zbynek Vyskovsky - kvr000 On

You definitely can't in such way. Not only that it's unreliable and inconsistent across various processors but can be easily optimized out by JIT.

9
phflack On

There is a good chance that your empty for loop will be optimized and removed.

Instead, to pass the time it would be better to use Thread.sleep(long time) inside of a while loop to check and make sure the correct amount of time has passed

long timeToWait = 500;
long startTime = System.currentTimeMillis();
while(startTime + timeToWait > System.currentTimeMillis())
    Thread.sleep(startTime + timeToWait - System.currentTimeMillis());
//do stuff after the .5 second wait

Another way, not as good as Thread.sleep(), is to use a while loop until the correct time

long timeToWait = 500;
long startTime = System.currentTimeMillis();
while(startTime + timeToWait > System.currentTimeMillis());
//do stuff after the .5 second wait

I would also not recommend using a for loop with processing inside to attempt to pass time due to pipelining. The checking statement will fly by super fast once the processor realizes that it's almost always going to be true while processing.