Skip to content

Make Uuids have better random distribution #494

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import java.util.Set;
import java.util.SplittableRandom;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -232,7 +233,7 @@ private static String getProcessPiece() {
}
}
if (pid == null) {
pid = new Random().nextInt();
pid = ThreadLocalRandom.current().nextInt();
LOG.warn("Could not determine PID, falling back to a random integer: {}", pid);
}
ClassLoader loader = Uuids.class.getClassLoader();
Expand Down Expand Up @@ -281,7 +282,7 @@ private static long makeClockSeqAndNode() {
*/
@NonNull
public static UUID random() {
return random(new Random());
return random(ThreadLocalRandom.current());
}

/**
Expand All @@ -300,7 +301,13 @@ public static UUID random() {
@NonNull
public static UUID random(@NonNull Random random) {
byte[] data = new byte[16];
random.nextBytes(data);
for (int i = 0; i < 16; i += 4) {
int rnd = random.nextInt();
data[i] = (byte) (rnd >>> 24);
data[i + 1] = (byte) (rnd >>> 16);
data[i + 2] = (byte) (rnd >>> 8);
data[i + 3] = (byte) rnd;
}
return buildUuid(data, 4);
}

Expand Down
Loading