system can not handle events fired on nanoseconds, why?

329 Views Asked by At

I really seek a logical explanation regarding the following. I have a timed task

static TimerTask timedTask = new TimerTask() {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("timed task");
    }
};

Timer timer = new Timer();
timer.schedule(timedTask, (long) logfile.getFileHash().get(1).getTimeStampInNano());

when i run that code, nothing shows up in the console, but wen I change it to:

Timer timer = new Timer();
timer.schedule(timedTask, (long) logfile.getFileHash().get(1).getTimeStampInMilli());

the console displays the message in the run() method. It seems to me that the system could not manage to handle time in nanoseconds because they are faster than the system clock. But how it is possible while there is a method called System.nanoTime(), which means the system should be able to recognize that a tasks starts at specific nano seconds.

2

There are 2 best solutions below

1
On BEST ANSWER

The api documentation on System.nanoTime() says:

This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) - no guarantees are made except that the resolution is at least as good as that of currentTimeMillis().

As such, the JVM might not be able to see difference in time that are smaller than 1 millisecond.

3
On

I'm not sure I understand the actual question, and the information given in the accepted answer looks correct as far as it goes. But for the method Timer.schedule(TimerTask, long), the long value is a delay measured in milliseconds. It does not know or care whether the long was originally a number of nanoseconds. Since that is billionths of a second instead of thousandths, you're going to wait many orders of magnitude longer than if it were in milliseconds.