7

I want to add a delay of 0.488 ms to my java code. but thread.sleep() and Timer functions only allow a granularity of millisecond. How do I specify a delay amount below that level ?

Aditya
  • 195
  • 3
  • 4
  • 12

3 Answers3

16

Since 1.5 you can use this nice method java.util.concurrent.TimeUnit.sleep(long timeout):

TimeUnit.SECONDS.sleep(1);
TimeUnit.MILLISECONDS.sleep(1000);
TimeUnit.MICROSECONDS.sleep(1000000);
TimeUnit.NANOSECONDS.sleep(1000000000); 
  • 1
    You can't rely on this if you want to wait small number of microseconds. The only way to do this is to busy wait on a thread. – Dan Oct 26 '15 at 18:19
  • These functions are defined as calling `Thead.sleep(long millis, int nanos);`, which in all versions of OpenJDK as of yet end up calling Thread.sleep(long millis)` with nanos rounded to the nearest millis. – TheCycoONE Jul 05 '22 at 02:28
4

You can use Thread.sleep(long millis, int nanos)

Note that you cannot guarantee how precise the sleep will be. Depending on your system, the timer might only be precise to 10ms or so.

Cameron Skinner
  • 51,692
  • 2
  • 65
  • 86
  • In WIndows JDK1.6.0_37, this method just add one millisecond, and call Thread.sleep(). It is fully ignoring nanos time. – kornero Nov 27 '12 at 06:25
  • 1
    @kornero: That's exactly why you cannot guarantee the precision of this method :) Nevertheless, on some systems you can get sub-millisecond precision. – Cameron Skinner Nov 27 '12 at 07:01
  • Not for any version of openjdk. If there's a JDK that implements this I haven't seen it. – TheCycoONE Jul 05 '22 at 02:20
3

TimeUnit.anything.sleep() call Thread.sleep() and Thread.sleep() rounded to milliseconds, all sleep() unusable for less than millisecond accuracy

Thread.sleep(long millis, int nanos) implementation:

public static void sleep(long millis, int nanos) throws java.lang.InterruptedException
{
  ms = millis;
  if(ms<0) {
    // exception "timeout value is negative"
    return;
  }
  ns = nanos;
  if(ns>0) {
    if(ns>(int) 999999) {
      // exception "nanosecond timeout value out of range"
      return;
    }
  }
  else {
    // exception "nanosecond timeout value out of range"
    return;
  }
  if(ns<500000) {
    if(ns!=0) {
      if(ms==0) { // if zero ms and non-zero ns thread sleep 1ms
        ms++;
      }
    }
  }
  else {
    ms++;
  }
  sleep(ms);
  return;
}

same situation is with method wait(long, int);