what is the most precise time I can get in JDK?

David Holmes David.Holmes at oracle.com
Wed Nov 16 08:42:13 UTC 2011

On 16/11/2011 6:09 PM, Weijun Wang wrote:
> Yes, I know nanoTime() is precise, but how can I get a clock time from it? I
> have tried to record a currentTimeMillis() value when the program starts and
> then use the elapse of the nanaTime() to get a current time. This will break
> if the user adjusts the system clock during the program execution.
> One solution is to keep tracking the changing of both currentTimeMillis()
> and nanoTime(). If the change of one has a difference (say, > 1 sec) from
> the other one, it means a system clock change and I can quickly reset my
> time to currentTimeMillis().

What you have tried is pretty much all you can do. nanoTime is not connected 
to to the time-of-day. If you need to make a connection then you need to 
make it and keep it synchronized.


> Thanks
> Max
> On 11/16/2011 03:23 PM, David Holmes wrote:
>> Hi Max,
>> On 16/11/2011 2:55 PM, Weijun Wang wrote:
>>> I need a precise time, and is currently using java.util.Date, which knows
>>> about milliseconds, but unfortunately the precision is only 10-15
>>> milliseconds on a Windows.
>>> In fact, I don't really need it to be so correct. My requirements are:
>>> 1. It's enough correct, say, at least as correct as Date.
>>> 2. It's precise in a relative sense, i.e. it changes fast
>>> 3. It should be monotonic, i.e. it grows, unless the user adjusts the
>>> system
>>> clock
>> There are only two time source available:
>> 1. The time-of-day clock
>> This is what Date reports and is also what System.currentTimeMillis
>> reports. It only has millisecond precision. It's rate of update is
>> dependent on the OS - for Windows that is typically every 10ms or every
>> 15ms depending on version.
>> 2. The high resolution time source
>> This is what System.nanoTime reports. It has nanosecond precision, but
>> again depending on the OS it's resolution (update rate) will vary. The
>> update rate should easily be in the tens of microseconds. It should be
>> monotonic non-decreasing but it is not connected to the time-of-day
>> clock (and so should not be affected by any changes therein).
>> I have an old blog entry on this:
>> http://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks
>> David
>> -----

More information about the core-libs-dev mailing list