Kaz Wolfe Kaz Wolfe - 1 year ago 68
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 {
} catch (InterruptedException ex) {
gotMessage = MessageHandler.getResponse(sendTime, phone);
return gotMessage;

This code itself is called through a
, 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
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?

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download