Java 8 introduces the java.time.Clock interface, which should allow me to mock out system time calls effectively (awesome!).
I'd like to naively replace calls to System.currentTimeMillis()
with calls to someClock.millis()
, but it isn't clear to me that these two clocks will actually return the same values in all cases based the caviet given in the Clock.system*
docs which state that they use "... the best available system clock". System.currentTimeMillis()
doesn't specify any similar claims about using the best available clock.
Well no, you can't guarantee it will be exactly the same, because
The system factory methods provide clocks based on the best available system clock. This may use System.currentTimeMillis(), or a higher resolution clock if one is available
So it explicitly states that it may use a better clock, which means it absolutely may be different.
Even if you analyze all existing implementations and discover they're all using System.currentTimeMillis()
you are explicitly not guaranteed that things will stay that way, so relying on it would be invalid.
Whether that's close enough for your purposes is really down to your application and personal preference.
JDK 9 will have a higher precision clock, see issue 8068730. As such, System.currentTimeMillis()
and Clock.systemUTC().millis()
may differ. Consider that today, on Windows, the currentTimeMillis
returns a low-precision value which will almost certainly be better in JDK 9, even at the millisecond level.
One option to guarantee the same behaviour, is to implement the Clock
class yourself, calling currentTimeMillis
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With