You get the best accuracy and precision Java can give you from Instant.now()
. Whether this is enough to solve your problem, I dare not tell. Certainly on a normal computer there is no way to get nanosecond accuracy.
You may need to play some tricks with adding an artificial nanosecond in case Instant.now()
returns the same value twice.
Or simple use the trick mentioned in your link:
Introduce an arbitrary new tag to enforce uniqueness.
For the trick of adding an artificial nanosecond you may for example use something like the following:
public class TimeProvider {
Instant last = Instant.now().minusSeconds(1);
Instant getUniqueInstant() {
Instant result = Instant.now();
if (! result.isAfter(last)) {
result = last.plusNanos(1);
}
last = result;
return result;
}
}
When I draw times in rapid succession from this class on my computer, I get results like below. It would seem from the output (the way I interpret it):
- My JVM cannot get higher precision than microseconds (6 decimals on the seconds) from the system clock.
- An artificial nanosecond is added now and then to keep the instants unique.
.
2018-08-29T15:18:35.617616001Z
2018-08-29T15:18:35.617617Z
2018-08-29T15:18:35.617618Z
2018-08-29T15:18:35.617618001Z
2018-08-29T15:18:35.617619Z
2018-08-29T15:18:35.617619001Z
2018-08-29T15:18:35.617620Z
2018-08-29T15:18:35.617620001Z
2018-08-29T15:18:35.617621Z
2018-08-29T15:18:35.617621001Z
2018-08-29T15:18:35.617622Z
2018-08-29T15:18:35.617623Z
2018-08-29T15:18:35.617623001Z
2018-08-29T15:18:35.617624Z
2018-08-29T15:18:35.617624001Z
2018-08-29T15:18:35.617625Z
2018-08-29T15:18:35.617625001Z
2018-08-29T15:18:35.617626Z
2018-08-29T15:18:35.617626001Z
2018-08-29T15:18:35.617627Z
2018-08-29T15:18:35.617627001Z
2018-08-29T15:18:35.617628Z
2018-08-29T15:18:35.617631Z
2018-08-29T15:18:35.617634Z
2018-08-29T15:18:35.617635Z
2018-08-29T15:18:35.617636Z
2018-08-29T15:18:35.617636001Z
2018-08-29T15:18:35.617637Z
2018-08-29T15:18:35.617637001Z
2018-08-29T15:18:35.617638Z