Skip to content

Commit 7bc5cfc

Browse files
committed
Fix Uuids.random to get better distribution
Before this commit it used `random.nextBytes` which made it generate an `int` and crop it to `byte`, since it is quasi random, it produces bad distribution and lead to have more UUID collisions.
1 parent fcec90c commit 7bc5cfc

File tree

1 file changed

+7
-1
lines changed
  • core/src/main/java/com/datastax/oss/driver/api/core/uuid

1 file changed

+7
-1
lines changed

core/src/main/java/com/datastax/oss/driver/api/core/uuid/Uuids.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -301,7 +301,13 @@ public static UUID random() {
301301
@NonNull
302302
public static UUID random(@NonNull Random random) {
303303
byte[] data = new byte[16];
304-
random.nextBytes(data);
304+
for (int i = 0; i < 16; i += 4) {
305+
int rnd = random.nextInt();
306+
data[i] = (byte) (rnd >>> 24);
307+
data[i + 1] = (byte) (rnd >>> 16);
308+
data[i + 2] = (byte) (rnd >>> 8);
309+
data[i + 3] = (byte) rnd;
310+
}
305311
return buildUuid(data, 4);
306312
}
307313

0 commit comments

Comments
 (0)