0

i'm running a JavaServlet and as JavascriptApp on the same machine.

The servlet outputs the current time:

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletOutputStream os = resp.getOutputStream();
    os.print("" + System.currentTimeMillis());
}

The JS Gets the time:

$.get("UserdataServlet", function(data) {
            console.log("dy " + data);
            console.log("my " + Date.now());
        });

and prints sometimes values like this:

dy 1433690185937
my 1433690185935

how can that be? The time on the Servlet is taken before the Date.now() in the javascript? And both are running on the same machine.

"my 1433690185935" should always be greater or at least equal than "dy 1433690185937". But how can it get smaller

Is it some kind of optimisation from the browser?

some more examples:

GET http://localhost:8081/Planetserverlinux/UserdataServlet
dy 1433691257707
my 1433691257717

GET http://localhost:8081/Planetserverlinux/UserdataServlet
dy 1433691258716
my 1433691258719

GET http://localhost:8081/Planetserverlinux/UserdataServlet
dy 1433691259700
my 1433691259715

GET http://localhost:8081/Planetserverlinux/UserdataServlet
dy 1433691260700
my 1433691260720

GET http://localhost:8081/Planetserverlinux/UserdataServlet
dy 1433691261700
my 1433691261712

GET http://localhost:8081/Planetserverlinux/UserdataServlet
dy 1433691262704
my 1433691262701
wutzebaer
  • 14,365
  • 19
  • 99
  • 170

1 Answers1

3

Since you are running on a windows machine the Java call to get the time is rounded to the nearest 16 milliseconds. The Javascript call in not restricted to this limitation.

With this knowledge it is quite easy for one to be different, and out of order, to the other.

See this extended discussion on SO about precision and accurracy of Java Time

Community
  • 1
  • 1
Brett Walker
  • 3,566
  • 1
  • 18
  • 36
  • or do you mean that System.currentTimeMillis() is already rounded? – wutzebaer Jun 07 '15 at 15:44
  • What do you mean by correct? What accuracy are you looking for? Clocks on computer are never accurate and they do drift. – Brett Walker Jun 07 '15 at 15:44
  • i mean: at which point does the time get rounded? Already in the Java-Part? – wutzebaer Jun 07 '15 at 15:45
  • 1
    Yes, `System.currentTimeMillis()` is rounded. On other platforms this is not so. It is a results of the JVM calling the Time API on the Windows Platform. It is Windows, not Java that is responsible for this artifact. – Brett Walker Jun 07 '15 at 15:46
  • does System.nanoTime underly this effect, too? – wutzebaer Jun 07 '15 at 15:49
  • If you are really worried about accuracy of the time then you have to move away from Java. The time for the JVM to burrow through the Windows Time API to access the relevant timer swaps the accuracy of the timers. – Brett Walker Jun 07 '15 at 15:51