Home > Mobile >  How to sleep a thread in java for few milliseconds?
How to sleep a thread in java for few milliseconds?

Time:09-29

I would like to sleep a thread for 1ms. I used to implement the sleep in java code with Thread.sleep(x) being x the amout of milliseconds that I wnat to sleep. However, I saw that it won't work because Sleep relinquishes the thread's timeslice. That is, the minimum amount of time a thread will actually stall is determined by the internal system timer but is no less than 10 or 25ms (depending upon OS).

Is there any way to implement it for few milliseconds e.g. 10 ms or 1 ms?

CodePudding user response:

"Relinquish the thread's timeslice" and "sleep" both mean approximately the same thing. If you want a delay that does not "sleep," then you need your thread to "spin," doing nothing, for that amount of time. E.g.,

static void spin(long delay_in_milliseconds) {
    long delay_in_nanoseconds = delay_in_milliseconds*1000000;
    long start_time = System.nanoTime();
    long end_time = start_time   delay_in_nanoseconds;
    while (true) {
        long now = System.nanoTime();
        if (now >= end_time) {
            break;
        }
    }
}

A call to spin(n) will burn CPU time for n milliseconds, which is the only way to delay a thread without "relinquishing the time slice."


P.S., You said, "I saw that it [sleep()] won't work..." Why is that? What did you see? Did you actually measure the performance of your program, and find that it is not satisfactory? or is your program failing to meet some hard real-time requirement? If your program has real-time requirements, then you might want to read about the "Real-time Specification for Java" (RTSJ).

See Also, https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/System.html#nanoTime()

CodePudding user response:

I don't think the os will let you do that. My best bet is to do, maybe a small loop that would consume some time. But then also be beware of the java compiler as it may and can eliminate pointless loops by performing dead code analysis. So just store the result of the loop and in the loop, perform some divisions or modulos, these are great for consuming time.

But overall, its all a hack, and you should generally refrain from doing such small delays. Typically they do not improve user experience but still result in convoluted code

  • Related