Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer: period less than a millisecond

Tags:

java

timer

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

like image 966
Hamal000 Avatar asked May 10 '12 14:05

Hamal000


3 Answers

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.

like image 122
assylias Avatar answered Nov 16 '22 12:11

assylias


Thread.sleep(long millis, int nanos)

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

like image 4
Marko Topolnik Avatar answered Nov 16 '22 10:11

Marko Topolnik


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.)

like image 2
yshavit Avatar answered Nov 16 '22 10:11

yshavit