Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to naively replace System.currentTimeMillis() with Clock.systemDefaultZone().millis()?

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.

like image 797
idbentley Avatar asked May 15 '15 20:05

idbentley


2 Answers

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.

like image 179
CupawnTae Avatar answered Oct 29 '22 05:10

CupawnTae


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.

like image 26
JodaStephen Avatar answered Oct 29 '22 05:10

JodaStephen