简体   繁体   中英

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.

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.

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

Or you can decorate ScheduledThreadPoolExecutor from Java library.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM