Skip to content

Commit 86ad13d

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

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

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

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,12 @@ 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+
* @param timestamp
61+
* @return
62+
*/
5763
private static long nanos(Instant timestamp) {
5864
return (long) ((timestamp.getNano() % 1_000_000L) * 0.004096);
5965
}
@@ -64,9 +70,9 @@ public State getNextState() {
6470
return new State( now, randomSequence() );
6571
}
6672
else {
67-
final long nextSequence = lastSequence + Holder.numberGenerator.nextLong( 0xFFFF_FFFFL );
68-
return nextSequence > MAX_RANDOM_SEQUENCE
69-
? new State( lastTimestamp.plusNanos( 250 ), randomSequence() )
73+
final long nextSequence = Holder.numberGenerator.nextLong( MAX_RANDOM_SEQUENCE + 1 );
74+
return lastSequence >= nextSequence
75+
? new State( lastTimestamp.plusNanos( 250 ), nextSequence )
7076
: new State( lastTimestamp, nextSequence );
7177
}
7278
}
@@ -118,7 +124,7 @@ public UUID generateUuid(final SharedSessionContractImplementor session) {
118124
| state.nanos() & 0xFFFL,
119125
// LSB bits 0-1 - variant = 4
120126
0x8000_0000_0000_0000L
121-
// LSB bits 2-15 - pseudorandom counter
127+
// LSB bits 2-63 - pseudorandom counter
122128
| state.lastSequence
123129
);
124130
}

0 commit comments

Comments
 (0)