Prashant Pandey
Prashant Pandey

Reputation: 4642

Difference B/W Clock.systemUTC() And System.currentTimeMillis()

Clock.systemUTC() docs say that this method may use System.currentTimeMillis() or a higher resolution clock if available. What clock does System.currentTimeMillis() use then? Can there be a difference in the granularity of these two values?

Upvotes: 2

Views: 1061

Answers (1)

Andreas
Andreas

Reputation: 159114

Can there be a difference in the granularity of these two values?

The Clock class has 2 methods for retrieving the current time:

Since instant() returns an Instant, which can represent time with a precision of nano-seconds, the answer is obvious.

Answer: Yes.


What clock does System.currentTimeMillis() use then?

If you look at the source code of Clock.systemUTC(), you will find that it uses an internal SystemClock class. In a comment in the millis() method, it says (quoting Java 15):

System.currentTimeMillis() and VM.getNanoTimeAdjustment(offset) use the same time source - System.currentTimeMillis() simply limits the resolution to milliseconds.
So we take the faster path and call System.currentTimeMillis() directly - in order to avoid the performance penalty of VM.getNanoTimeAdjustment(offset) which is less efficient.

Answer: System.currentTimeMillis() and Clock.instant() use the same time source.

Upvotes: 3

Related Questions