4

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?

Community
  • 1
  • 1
Anonymous
  • 3,334
  • 3
  • 35
  • 50

4 Answers4

4

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
3

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.

Mike Partridge
  • 5,128
  • 8
  • 35
  • 47
1

The idea is probably to introduce a pause in the computation, but if the pause is interrupted, then that means that the computation should not continue. Why a pause is needed is impossible to say without seeing the surrounding (calling) code.

Roger Lindsjö
  • 11,330
  • 1
  • 42
  • 53
0

I guess they want to pause for at least x seconds; if for some reason the Thread was unable to sleep that long, they'd use the return value to call the method again

Slash
  • 496
  • 2
  • 8