Lately I made a very basic program. A time counter which has the ability of pausing. It was working with 3 threads, 2 for Swing and 1 for the main thread.
For this program there should be a delta time counting part in the main thread. I made a very basic system like that;
while(true)
{
long now = System.currentTimeMillis();
if(!sessionPaused)
{
if(now-programLastMs>1000)
{
save();
programLastMs = now;
}
sessionMs += now-sessionPrevMs;
overallMs += now-sessionPrevMs;
sessionPrevMs = now;
sessionLabel.setText(formatMillis("This Session:<br/>",sessionMs));
overallLabel.setText(formatMillis("Overall:<br/>", overallMs));
}
}
This code above caused high CPU usage. I then replaced that code chunk with:
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
long now = System.currentTimeMillis();
if(!sessionPaused)
{
if(now-programLastMs>1000)
{
save();
programLastMs = now;
}
sessionMs += now-sessionPrevMs;
overallMs += now-sessionPrevMs;
sessionPrevMs = now;
sessionLabel.setText(formatMillis("This Session:<br/>",sessionMs));
overallLabel.setText(formatMillis("Overall:<br/>", overallMs));
}
}
}, 0, 1);
And the problem was gone. I just wonder the reason of that. Also what is the optimum way of creating a program loop?
while(true)loop doesn't make any pause, so the loop is constantly running and constantly eating CPU. The scheduling makes yourrunmethod execute, only when it is scheduled to.runmethod, but 50 nanoseconds is really low, do you need such a high frequency ? However as you have seen it, it is better to let your application breathe, so either use a scheduler, or add aThread.sleepto yourwhileloop.