Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monotonically increasing time in Java?

Tags:

In a Java application I want to be able to take a timestamp at the start of an operation and be able to periodically check how long the operation has been running. The catch is: I do not want to be impacted by the Network Time Protocol moving the clock around, or the admin changing the time, or anything which can abruptly adjust the time of day. I want a monotonically increasing time value. I believe this rules out java.util.Date, Time, and Calendar.

Is there some source of a monotonically increasing timestamp in the JRE?

like image 432
DGentry Avatar asked Jan 12 '09 03:01

DGentry


People also ask

What is monotonic time?

A monotonic clock is a time source that won't ever jump forward or backward (due to NTP or Daylight Savings Time updates).

Is Java nanoTime monotonic?

nanoTime() is monotonic (if the underlying system supports it).


2 Answers

Have you considered using System.nanoTime()?

It is only meaningful in working out elapsed time between two events. Since the documentation states that it is not related to any system or wall time I believe it could be used in your sitatuion.

like image 154
hhafez Avatar answered Sep 24 '22 09:09

hhafez


JodaTime has a class to do this. It is called Duration.

"They have no chronology or time zone, and consist solely of the millisecond duration."

Also you could set your Date stamp to Greenwich time and the Network Time Protocol should not be an issue.

like image 41
WolfmanDragon Avatar answered Sep 22 '22 09:09

WolfmanDragon