Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Most optimal way to poll for timeout

Tags:

java

I have code such that:

while(isResponseArrived)
   Thread.yield();

But what I'd really like to do is something like this:

long startTime = System.currentTimeInMilliseconds();

while(isResponseArrived)
{
   if(isTimeoutReached(startTime))
       throw new TimeOutExcepton(); 
   Thread.yield();
}

I'm not yet sure about throwing an exception or not (it's not important for this question), but what I'd like to know is how to make it as performant as possible, so I'm not chugging away on the processor. In other words how can I make isTimeoutReached(long startTime) as performance friendly as possible.

I tested:

for(int x=0; x<99999999; x++)
    System.nanoTime();

versus

for(int x=0; x<99999999; x++)
    System.currentTimeInMilliseconds();

And the difference was minimal, less than 10% in terms of time to complete

I also look at using Thread.sleep(), but I really want the user to be notified as quickly as possible if there's an update and the processor is just waiting. Thread.yield() doesn't get the processor churning, it's just a NOP, giving anyone else processor priority, until it's good to go.

Anyways, what's the best way to test for a timeout without throttling the CPU? Is this the right method?

like image 471
Stephane Grenier Avatar asked Dec 04 '25 14:12

Stephane Grenier


1 Answers

I think it would be more efficient to use wait / notify

boolean arrived;

public synchronized void waitForResponse(long timeout) throws InterruptedException, TimeoutException {
    long t0 = System.currentTimeMillis() + timeout;
    while (!arrived) {
        long delay = System.currentTimeMillis() - t0;
        if (delay < 0) {
            throw new TimeoutException();
        }
        wait(delay);
    }
}

public synchronized void responseArrived() {
    arrived = true;
    notifyAll();
}
like image 171
Evgeniy Dorofeev Avatar answered Dec 07 '25 04:12

Evgeniy Dorofeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!