Search code examples
javamultithreadingsleepmilliseconds

How to sleep a thread in java for few milliseconds?


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 want to sleep. However, I saw that it won't work with few amount of milliseconds (1 ms) 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?


Solution

  • "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();
        while (true) {
            long now = System.nanoTime();
            long time_spent_sleeping_thus_far = now - start_time;
            if (time_spent_sleeping_thus_far >= delay_in_nanoseconds) {
                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()