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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With