Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What might be the purpose of sleeping for just to see if the thread gets interrupted?

I came across some Java code that has a method containing the following:

static boolean waitForSeconds(long seconds) {
    try {
        Thread.sleep(seconds * 1000);
    } catch (InterruptedException ex) {
        return false;
    }
    return true;
}

What might be the purpose of this? The return value is used to determine whether a computation should continue. It seems strange to me to try to sleep for 1 second for the sole purpose of checking whether the thread was interrupted during that second.

Is the code that calls this method trying to accomplish the same thing as thread.isInterrupted()? Whatever it is trying to do, is there a better way?

The call to waitForSeconds appears at the top of another method, not inside of a loop, so if this code does intend to wait for a second for some purpose in addition to checking for an interrupt, it seems like it would be checking in the wrong place. Wouldn't it be better to put the sleep near the loop, where it is clearer what it is doing?

For the last question, please reply here instead:

Is it clearer to sleep near a function call in a loop or in the function call itself?

like image 449
Anonymous Avatar asked Feb 23 '23 00:02

Anonymous


2 Answers

The purpose is to pause.

Check the code calling the outer method to try to see why they want to pause.
They may want to save CPU or network.

like image 106
SLaks Avatar answered Feb 24 '23 12:02

SLaks


The purpose of the method is to cause the thread execution to stop for the specified number of seconds. The catch clause allows the method to communicate to the caller that the thread was interrupted, as opposed to the time period expiring.

like image 29
Mike Partridge Avatar answered Feb 24 '23 14:02

Mike Partridge