Kaz Wolfe Kaz Wolfe - 4 months ago 12
Java Question

How would I avoid using Thread.sleep()?

I have the below snippet of code, designed to check if a message was sent to a phone number:

public static boolean checkMessages(long sendTime, String phone) {
boolean gotMessage = false;

while (!gotMessage) {
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
gotMessage = MessageHandler.getResponse(sendTime, phone);
}
return gotMessage;
}


This code itself is called through a
CompletableFuture
, so it can run in parallel with another check. If neither check is satisfied within a certain amount of time, both will expire.

Now, according to my IDE and this site, using
Thread.sleep()
is bad for a number of reasons, so I'd like to remove it from my code somehow.

Is there a way to do this such that this method will only ever return true, like it currently is?




MessageHandler.getResponse()
is a handler I wrote to check if I received a text message containing a specific (hardcoded) string of text from a specific phone number. It does block execution until it finishes checking, but the API I'm using has very aggressive rate limits. The API offers no callbacks -- it must manually be called.

Answer

It's not very clear what your whole code does. As commented by others, knowing what MessageHandler does would add some context.

The Thread.sleep static invocation will make the current thread sleep for at least the given amount of time,

subject to the precision and accuracy of system timers and schedulers

(see API)

If your MessageHandler.getResponse invocation blocks before returning, then you probably don't need to sleep at all.

However, if this task is repeated "endlessly", you probably want to use a ScheduledExecutorService instead, and run it based on a schedule.

Bottomline, Thread.sleep is not "bad practice" per se, but you seldom need to actually use it.