Is Thread.sleep better than continually checking to see if a condition is met?

225 Views Asked by At

I want this program to run indefinitely and I am not sure of the best way to maximize cpu and memory efficiency. I have created a thread that handles responses from a server, these responses will come back every 20 seconds or so. However, I have to make sure that the server is still sending responses, otherwise I must get responses from a new server. Every time a response comes back, the current system time is stored in 'lastRTime'. Is there a better alternative to Thread.sleep() here? This is at the end of my main thread.

while(true) {
    Thread.sleep(checkInterval);
        if (System.currentTimeMillis()-lastRTime > timeDiffThreshold) {
            pmsi.beginClose();    //Close the current connection
            makeConnection(backupHost,backupPort);
        }
    }
}

Would it be better to simply not sleep?

1

There are 1 best solutions below

0
On BEST ANSWER

I think that the best alternative (but not the must-be) is to use ScheduledExecutor and submit your checking to run after checkInterval. In case if you would get response earlier, you can cancel that task and resubmit with new delay.

So i would be like that (pseudocode):

  1. schedule response check to run after checkInterval
  2. Handle response
  3. If "check" task is still pending, cancel it, update lastRTime, and reschedule (point 1)

If check task would fire, then reschedule again.

This way you ommit waiting period between lastRTime and Thread.sleep() invokation timestamp