7

As the title, is there a way to get the Timer working under the threshold of a millisecond?

My question is similar the following one, but it is intended for Java: Thread.Sleep for less than 1 millisecond

Community
  • 1
  • 1
Hamal000
  • 516
  • 1
  • 5
  • 25

4 Answers4

11

If you want to sleep, Thread.sleep has 2 methods, one of which accepts nanoseconds. If you want to schedule a task, you can use a ScheduledExecutorService which schedule methods can use nanoseconds too.

As explained by @MarkoTopolnik, the result will most likely not be precise to the nanosecond.

assylias
  • 321,522
  • 82
  • 660
  • 783
4
Thread.sleep(long millis, int nanos)

Also check out this answer with details on issues with this on Windows.

Community
  • 1
  • 1
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
2

You could wait on an object that nobody will notify...

synchronized (someObjectNobodyWillNotify) {
    try {
        someObjectNobodyWillNotify.wait(0, nanosToSleep);
    }
    catch (InterruptedException e) {
        Thread.interrupt();
    }
}

(In this scenario, I'm guessing spurious wakeups are okay. If not, you need to record your System.nanoTime() at the start and wrap the wait in a loop that checks that enough time has elapsed.)

yshavit
  • 42,327
  • 7
  • 87
  • 124
1

The java.util.concurrent package uses TimeUnit for timing. TimeUnit has a NANOSECONDS field.

PeterMmm
  • 24,152
  • 13
  • 73
  • 111