Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we use Thread.sleep( ) when doing something with timeout?

Tags:

java

Consider the following two blocks:

    // block one
    long start = System.currentTimeMillis();
    while (System.currentTimeMillis() - start < TIMEOUT) {
        if( SOME_CONDITION_IS_MET ) {
            // do something
            break;
        } else {
            Thread.sleep( 100 );
        }
    }

    // block two
    long start = System.currentTimeMillis();
    while (System.currentTimeMillis() - start < TIMEOUT) {
        if( SOME_CONDITION_IS_MET ) {
            // do something
            break;
        }
    }

The difference between the two is that the first one has a Thread.sleep(), which seemingly can reduce condition checking in while and if. However, is there any meaningful benefit by having this sleep, assuming the if condition doesn't have a heavy computation? Which one would you recommend for implementing timeout?

like image 791
JBT Avatar asked Jul 08 '26 23:07

JBT


1 Answers

One key difference is that the second method involves busy waiting. If SOME_CONDITION_IS_MET doesn't involve any I/O, the second approach will likely consume an entire CPU core. This is a wasteful thing to do (but could be perfectly reasonable in some -- pretty rare -- circumstances). On the flip side, the second approach has lower latency.

I agree with Boris that, in a general setting, both approaches are basically hacks. A better way would be to use proper synchronization primitives to signal the condition.

like image 117
NPE Avatar answered Jul 11 '26 13:07

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!