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?
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):
checkInterval
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