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

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 former has Thread.sleep (), which apparently can reduce condition checking in while

and if

. However, is there any meaningful benefit to this sleep if the condition is if

not heavily computed? Which one do you recommend for implementing a timeout?

+3


source to share


1 answer


One of the key differences is that the second method involves an expectation of an expectation . If it SOME_CONDITION_IS_MET

doesn't involve any I / O, the second approach is likely to consume the entire processor core. This is a wasteful thing (but it can be perfectly reasonable in some - rather rare cases). On the other hand, the second approach has lower latency.



I agree with Boris that in general terms both approaches are mostly hacks. It is best to use the correct synchronization primitives to signal state.

+2


source







All Articles