Skip to content

Commit 263f09d

Browse files
authored
Make Uuids have better random distribution (#494)
* Make Uuids use ThreadLocalRandom Before this commit `Uuids` used to initiate `Random `at the point when it needs a random number. Not only it is not effecient it also produced bad distribution which resulted in `should_generate_unique_random_uuids_Random` to fail, due to inability of `Uuids::random `generate unique vales. * 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 2a62541 commit 263f09d

File tree

1 file changed

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

1 file changed

+10
-3
lines changed

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

+10-3
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
import java.util.Set;
4040
import java.util.SplittableRandom;
4141
import java.util.UUID;
42+
import java.util.concurrent.ThreadLocalRandom;
4243
import java.util.concurrent.atomic.AtomicLong;
4344
import org.slf4j.Logger;
4445
import org.slf4j.LoggerFactory;
@@ -232,7 +233,7 @@ private static String getProcessPiece() {
232233
}
233234
}
234235
if (pid == null) {
235-
pid = new Random().nextInt();
236+
pid = ThreadLocalRandom.current().nextInt();
236237
LOG.warn("Could not determine PID, falling back to a random integer: {}", pid);
237238
}
238239
ClassLoader loader = Uuids.class.getClassLoader();
@@ -281,7 +282,7 @@ private static long makeClockSeqAndNode() {
281282
*/
282283
@NonNull
283284
public static UUID random() {
284-
return random(new Random());
285+
return random(ThreadLocalRandom.current());
285286
}
286287

287288
/**
@@ -300,7 +301,13 @@ public static UUID random() {
300301
@NonNull
301302
public static UUID random(@NonNull Random random) {
302303
byte[] data = new byte[16];
303-
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+
}
304311
return buildUuid(data, 4);
305312
}
306313

0 commit comments

Comments
 (0)