Skip to content

Commit 248c577

Browse files
Copilotsimbo1905
andcommitted
Fix uniqueThenTime to use most significant bits for time ordering
The previous implementation used the lower 44 bits of timeCounterBits, which only contained the lower 24 bits of the millisecond timestamp. This caused time wrapping every ~4.66 hours, breaking lexicographical sorting. Now uses the most significant 44 bits (timeCounter >> 20) to preserve long-term time ordering as intended. Co-authored-by: simbo1905 <322608+simbo1905@users.noreply.github.com>
1 parent 850b49c commit 248c577

File tree

1 file changed

+3
-2
lines changed

1 file changed

+3
-2
lines changed

json-java21/src/main/java/jdk/sandbox/demo/UUIDGenerator.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,12 +66,13 @@ public static UUID timeThenRandom() {
6666
/// └──────────────────────────────────────────────────────────────────────────────┘
6767
public static UUID uniqueThenTime(long uniqueMsb) {
6868
final int timeBits = 44;
69-
final long timeMask = (1L << timeBits) - 1;
7069
final int randomBits = 20;
7170
final int randomMask = (1 << randomBits) - 1;
7271
long timeCounter = timeCounterBits();
7372
long msb = uniqueMsb;
74-
long lsb = ((timeCounter & timeMask) << randomBits) | (getRandom().nextInt() & randomMask);
73+
// Take the most significant 44 bits of timeCounter to preserve time ordering
74+
long timeComponent = timeCounter >> (64 - timeBits); // timeBits is 44
75+
long lsb = (timeComponent << randomBits) | (getRandom().nextInt() & randomMask);
7576
return new UUID(msb, lsb);
7677
}
7778

0 commit comments

Comments
 (0)