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?
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.
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.
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