Kaz Wolfe
Kaz Wolfe

Reputation: 438

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.

Upvotes: 1

Views: 4880

Answers (3)

Jeremiah
Jeremiah

Reputation: 1145

I fully agree with Mena's response, but to offer an alternate implementation to Thread.sleep, you can use a CountdownLatch to perform your looping:

public void blockingWaitForMessage(long sendTime, String phone) throws InterruptedException{
        final CountDownLatch latch = new CountDownLatch(1);
        while (!latch.await(5, TimeUnit.SECONDS)) {
            if (MessageHandler.getResponse(sendTime, phone)) {
                latch.countDown();
            }
        }
    }

Using CountDownLatch.await handles both your boolean and temporal states!

Upvotes: 1

Orest Savchak
Orest Savchak

Reputation: 4569

You can use guava retrying library. Retryer It has nice API.

Or you can decorate ScheduledThreadPoolExecutor from Java library.

Upvotes: 0

Mena
Mena

Reputation: 48404

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.

Upvotes: 5

Related Questions