f4b6a3 / uuid-creator

UUID Creator is a Java library for generating Universally Unique Identifiers.
MIT License
432 stars 44 forks source link

ulid and timebased uuid has different precisions on Instant #34

Closed nimo23 closed 3 years ago

nimo23 commented 3 years ago

I have a question: I generated an ulid and an timebased uuid to a string. When extracting the time from it, the timebased uuid seems more precise:

// prints 2021-01-17T18:28:14.075
UlidUtil.extractInstant(ulid).atZone(ZoneId.systemDefault()).toLocalDateTime();
// prints 2021-01-17T18:28:14.075011200
UuidUtil.extractInstant(UuidCreator.fromString(timeUUID)).atZone(ZoneId.systemDefault()).toLocalDateTime()

Why is timebased uuid more precise than ulid?

fabiolimace commented 3 years ago

Hi, @nimo23

Both use System.currentTimeMillis() to get the current time.

The time-based UUID simulates high precision clock by adding a value between 0 and 9,999 to the timestamp. The RFC-4122 suggests the following in the section 4.2.1.2:

A high resolution timestamp can be simulated by keeping a count of
the number of UUIDs that have been generated with the same value of
the system time, and using it to construct the low order bits of the
timestamp.  The count will range between zero and the number of
100-nanosecond intervals per system time interval.

The lib uuid-creator used a counter until the version 3.2.0. Now it uses an accumulator (commits 2d7d6cf4067eebd0c5a017168a84671bed23cc12 and 79af4e6797da9a066e7e237f8779ed3f1d8c61e6).

These are the steps to generate a UUID timestamp:

  1. Get the current time using System.currentTimeMillis();
  2. Change it to Gregorian epoch;
  3. Multiply it the by 10,000;
  4. Add the accumulator to it;
  5. Return the resulting value.
nimo23 commented 3 years ago

Thanks for the explanation. So for high precision time based ID's, the timebased UUID is still the best;)