Skip to content

Commit f789726

Browse files
committed
HHH-19935 Make sure that increment to current sequence can not be zero
1 parent 014d311 commit f789726

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

hibernate-core/src/main/java/org/hibernate/id/uuid/UuidVersion7Strategy.java

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,13 @@ public long millis() {
5454
return lastTimestamp.toEpochMilli();
5555
}
5656

57+
/**
58+
* Sub-miliseconds part of timestamp (micro- and nanoseconds) mapped to 12 bit integral value.
59+
* Calculated as nanos / 1000000 * 4096
60+
*
61+
* @param timestamp
62+
* @return
63+
*/
5764
private static long nanos(Instant timestamp) {
5865
return (long) ((timestamp.getNano() % 1_000_000L) * 0.004096);
5966
}
@@ -64,9 +71,9 @@ public State getNextState() {
6471
return new State( now, randomSequence() );
6572
}
6673
else {
67-
final long nextSequence = lastSequence + Holder.numberGenerator.nextLong( 0xFFFF_FFFFL );
68-
return nextSequence > MAX_RANDOM_SEQUENCE
69-
? new State( lastTimestamp.plusNanos( 250 ), randomSequence() )
74+
final long nextSequence = randomSequence();
75+
return lastSequence >= nextSequence
76+
? new State( lastTimestamp.plusNanos( 250 ), nextSequence )
7077
: new State( lastTimestamp, nextSequence );
7178
}
7279
}
@@ -77,7 +84,7 @@ private boolean lastTimestampEarlierThan(Instant now) {
7784
}
7885

7986
private static long randomSequence() {
80-
return Holder.numberGenerator.nextLong( MAX_RANDOM_SEQUENCE );
87+
return Holder.numberGenerator.nextLong( MAX_RANDOM_SEQUENCE + 1 );
8188
}
8289
}
8390

@@ -118,7 +125,7 @@ public UUID generateUuid(final SharedSessionContractImplementor session) {
118125
| state.nanos() & 0xFFFL,
119126
// LSB bits 0-1 - variant = 4
120127
0x8000_0000_0000_0000L
121-
// LSB bits 2-15 - pseudorandom counter
128+
// LSB bits 2-63 - pseudorandom counter
122129
| state.lastSequence
123130
);
124131
}

0 commit comments

Comments
 (0)