Question

I am writing single threaded program that requires a pause after each operation. (pause = random value between 1 and 60 seconds).

So a wrote method like this:

public void freeze() throws InterruptedException {
    Thread.sleep(nextFreezeDurationSec * 1000);
    calculateNextFreezeDuration();
}

I discovered a problem while looking through program log. Аpparently, for some unknow for me reason, after 500-700 operations it puts my program to sleep for a much bigger amount of time (once it was greater than an hour)

And I wrote another method:

public void freeze() {
    long nextFreezeEnd = System.currentTimeMillis() + (nextFreezeDurationSec * 1000);
    while (System.currentTimeMillis() < nextFreezeEnd) {
      /*NOR*/
    }
    calculateNextFreezeDuration();
}

This one works fine. But it eats CPU like crazy.

I would be grateful for any advice on this issue.

Was it helpful?

OTHER TIPS

The second one is eating CPU because it is constantly calculating the nextFreezeDuration in the while loop.

Every time that it hits the while (which is infinitely until the while loop completes), it does a calculation. Research how to take a make it wait for a couple of milliseconds at least before letting it re-hit the while loop

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top