Search code examples
javaperformancefreezethread-sleep

Thread.sleep(60 * 1000) puts my program to sleep for half an hour or more


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.


Solution

  • It could be that another program is forcibly putting the JVM to sleep.