random: Random vs ThreadLocalRandom vs SecureRandom vs RandomGenerator module (seeds and a 2-output predictor, ranges and measured modulo bias, ThreadLocalRandom limits, SecureRandom algorithms and setSeed behaviour, the 13 java.util.random algorithms with split/jump, indicative timings), 16 contract tests
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b6F5pq1M5ni1bNw8gr
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
# random
|
||||
|
||||
Companion code for the ankurm.com post *"Random vs ThreadLocalRandom vs SecureRandom vs RandomGenerator in Java."*
|
||||
Module in `java-core-examples`, the Java-core series. All explanation lives in the post; this module holds the code and the captured output.
|
||||
|
||||
## Versions this was built and tested against
|
||||
|
||||
| Component | Version | Notes |
|
||||
|---|---|---|
|
||||
| JDK | 25.0.5.1 (Temurin, LTS) | `java.util.random` (JEP 356) arrived in JDK 17; `ThreadLocalRandom` in Java 7. |
|
||||
| JUnit Jupiter | 5.11.0 | |
|
||||
| Maven | 3.9.11 | |
|
||||
|
||||
## Quickstart
|
||||
|
||||
```bash
|
||||
export JAVA_HOME=/path/to/jdk-25
|
||||
mvn compile
|
||||
scripts/run.sh SeedDemo # one demo
|
||||
scripts/run-all.sh # regenerate every file in output/
|
||||
```
|
||||
|
||||
## What's in here
|
||||
|
||||
| File | What it shows | Output |
|
||||
|---|---|---|
|
||||
| `SeedDemo.java` + `Predictor.java` | Same seed, same sequence; `setSeed`; two `nextInt()` results predict the third. | `output/01` |
|
||||
| `RangeDemo.java` | `nextInt(origin, bound)`, the error messages, `% n` going negative, `Math.abs(MIN_VALUE)`, modulo bias measured. | `output/02` |
|
||||
| `ThreadLocalDemo.java` | `current()`, `setSeed` refused, one stream per thread, virtual threads. | `output/03` |
|
||||
| `SecureRandomDemo.java` | Which algorithm you get, `getInstanceStrong()`, tokens, what `setSeed` does. | `output/04` |
|
||||
| `RandomGeneratorDemo.java` | The interface, the default, the 13 algorithms in JDK 25, split and jump. | `output/05` |
|
||||
| `BenchmarkDemo.java` | Indicative timings (not JMH). Drifts between runs. | `output/06` |
|
||||
| `RandomContractTest.java` | Pins every claim above as an assertion, 16/16 passing. | `output/07` |
|
||||
|
||||
## License
|
||||
|
||||
MIT - see the [repo-wide LICENSE](../LICENSE).
|
||||
@@ -0,0 +1,19 @@
|
||||
|
||||
== Same seed, same sequence ==
|
||||
Random(42) #1: 30 63 48 84 70
|
||||
Random(42) #2: 30 63 48 84 70
|
||||
|
||||
== No seed: every instance starts somewhere different ==
|
||||
new Random() #1: 94 42 76
|
||||
new Random() #2: 86 37 29
|
||||
(these two lines differ on every run)
|
||||
|
||||
== setSeed rewinds an existing instance ==
|
||||
first draw before setSeed(7): 236, first draw after: 236
|
||||
|
||||
== Two outputs of an unseeded Random predict the third ==
|
||||
seen output 1 : 1471292627
|
||||
seen output 2 : 160425440
|
||||
predicted 3 : 239866061
|
||||
actual 3 : 239866061
|
||||
prediction correct: true
|
||||
@@ -0,0 +1,27 @@
|
||||
|
||||
== The right calls (upper bound is always exclusive) ==
|
||||
nextInt(10) 0..9 : 5
|
||||
nextInt(1, 7) 1..6 : 5
|
||||
nextInt(-5, 6) -5..5 : 3
|
||||
nextDouble() [0,1) : 0.4074398012118764
|
||||
nextDouble(2, 3) [2,3) : 2.036235382150368
|
||||
ints(5, 1, 7) : [5, 5, 5, 2, 2]
|
||||
|
||||
== Bad arguments fail loudly ==
|
||||
nextInt(0) -> bound must be positive
|
||||
nextInt(5, 5) -> bound must be greater than origin
|
||||
|
||||
== Trap 1: nextInt() % n can be negative ==
|
||||
1000 draws of nextInt() % 6, negative results: 397
|
||||
|
||||
== Trap 2: Math.abs(Integer.MIN_VALUE) is still negative ==
|
||||
Math.abs(Integer.MIN_VALUE) = -2147483648
|
||||
Math.abs(Integer.MIN_VALUE) % 10 = -8
|
||||
(nextInt() hits MIN_VALUE once in 2^32 calls, so tests never catch it)
|
||||
|
||||
== Trap 3: modulo bias ==
|
||||
3 random bits (0..7) % 3 -> counts of 0,1,2: [3, 3, 2]
|
||||
bound = 1,500,000,000, results below 647,483,648
|
||||
expected share if uniform : 0.4317
|
||||
(nextInt() >>> 1) % bound : 0.6031
|
||||
nextInt(bound) : 0.4315
|
||||
@@ -0,0 +1,12 @@
|
||||
|
||||
== The one correct way to call it ==
|
||||
ThreadLocalRandom.current().nextInt(1, 7) -> in 1..6: true
|
||||
|
||||
== It cannot be seeded ==
|
||||
setSeed(42) -> UnsupportedOperationException, message: null
|
||||
|
||||
== Each thread has its own state ==
|
||||
4 threads, distinct first values: 4 of 4
|
||||
|
||||
== Works the same on virtual threads ==
|
||||
virtual thread rolled a die: true
|
||||
@@ -0,0 +1,25 @@
|
||||
|
||||
== What new SecureRandom() gives you on this machine ==
|
||||
algorithm : NativePRNG
|
||||
provider : SUN
|
||||
|
||||
== getInstanceStrong() ==
|
||||
algorithm : NativePRNGBlocking
|
||||
securerandom.strongAlgorithms = NativePRNGBlocking:SUN,DRBG:SUN
|
||||
|
||||
== SecureRandom algorithms registered in this JDK ==
|
||||
DRBG (SUN)
|
||||
NativePRNG (SUN)
|
||||
NativePRNGBlocking (SUN)
|
||||
NativePRNGNonBlocking (SUN)
|
||||
SHA1PRNG (SUN)
|
||||
|
||||
== A session token: 32 random bytes = 256 bits ==
|
||||
length in characters: 43 (value differs on every run)
|
||||
|
||||
== Seeding: SHA1PRNG is deterministic, the default is not ==
|
||||
SHA1PRNG, same seed, same bytes: true
|
||||
NativePRNG, same seed, same bytes: false (setSeed only adds entropy; it does not make the output repeatable)
|
||||
|
||||
== It is also a RandomGenerator, so the range methods work ==
|
||||
nextInt(1, 7) in 1..6: true
|
||||
@@ -0,0 +1,39 @@
|
||||
|
||||
== The old classes already implement RandomGenerator ==
|
||||
Random -> rollDie in 1..6: true
|
||||
SecureRandom -> rollDie in 1..6: true
|
||||
SplittableRandom -> rollDie in 1..6: true
|
||||
ThreadLocalRandom -> rollDie in 1..6: true
|
||||
|
||||
== The default generator ==
|
||||
RandomGenerator.getDefault() : jdk.internal.random.L32X64MixRandom
|
||||
RandomGeneratorFactory.getDefault() : L32X64MixRandom
|
||||
|
||||
== Every algorithm this JDK ships (name, group, state bits, jumpable, splittable) ==
|
||||
L128X1024MixRandom LXM 1152 bits jumpable=false splittable=true
|
||||
L128X128MixRandom LXM 256 bits jumpable=false splittable=true
|
||||
L128X256MixRandom LXM 384 bits jumpable=false splittable=true
|
||||
L32X64MixRandom LXM 96 bits jumpable=false splittable=true
|
||||
L64X1024MixRandom LXM 1088 bits jumpable=false splittable=true
|
||||
L64X128MixRandom LXM 192 bits jumpable=false splittable=true
|
||||
L64X128StarStarRandom LXM 192 bits jumpable=false splittable=true
|
||||
L64X256MixRandom LXM 320 bits jumpable=false splittable=true
|
||||
Random Legacy 48 bits jumpable=false splittable=false
|
||||
SecureRandom Legacy 2147483647 bits jumpable=false splittable=false
|
||||
SplittableRandom Legacy 64 bits jumpable=false splittable=true
|
||||
Xoroshiro128PlusPlus Xoroshiro 128 bits jumpable=true splittable=false
|
||||
Xoshiro256PlusPlus Xoshiro 256 bits jumpable=true splittable=false
|
||||
|
||||
== Pick an algorithm by name, and seed it ==
|
||||
Xoshiro256PlusPlus seed 42 #1: 600 767 404
|
||||
Xoshiro256PlusPlus seed 42 #2: 600 767 404
|
||||
RandomGenerator.of("L64X128MixRandom") -> L64X128MixRandom
|
||||
|
||||
== Splittable: independent generators for parallel work ==
|
||||
first draw of 4 split children: 952 921 97 912
|
||||
|
||||
== Jumpable: provably non-overlapping streams ==
|
||||
jump distance : 3.402823669209385E38
|
||||
leap distance : 6.277101735386681E57
|
||||
original next: 600
|
||||
after jump next: 545
|
||||
@@ -0,0 +1,15 @@
|
||||
cores available: 2
|
||||
|
||||
== One thread: nanoseconds per nextInt(), 20000000 calls ==
|
||||
Random 8.5 ns/op
|
||||
SplittableRandom 0.7 ns/op
|
||||
ThreadLocalRandom 2.1 ns/op
|
||||
L32X64MixRandom (default) 2.9 ns/op
|
||||
Xoshiro256PlusPlus 2.7 ns/op
|
||||
SecureRandom 90.6 ns/op
|
||||
|
||||
== 4 threads sharing ONE instance, 5000000 calls each (wall time, ms) ==
|
||||
Random (shared) 987 ms
|
||||
SecureRandom (shared) 7329 ms
|
||||
ThreadLocalRandom.current() 37 ms
|
||||
checksum (ignore): -28432667108051
|
||||
@@ -0,0 +1,3 @@
|
||||
[INFO] Tests run: 16, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.159 s -- in com.ankurm.random.RandomContractTest
|
||||
[INFO] Tests run: 16, Failures: 0, Errors: 0, Skipped: 0
|
||||
[INFO] BUILD SUCCESS
|
||||
@@ -0,0 +1,47 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>com.ankurm</groupId>
|
||||
<artifactId>java-core-examples</artifactId>
|
||||
<version>1.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>random</artifactId>
|
||||
<name>random</name>
|
||||
<description>Random vs ThreadLocalRandom vs SecureRandom vs RandomGenerator (JEP 356): seeds, ranges, modulo bias, predictability, algorithm choice, and indicative timings.</description>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.11.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.13.0</version>
|
||||
<configuration>
|
||||
<release>25</release>
|
||||
<compilerArgs><arg>-Xlint:-deprecation</arg></compilerArgs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.2.5</version>
|
||||
<configuration>
|
||||
<argLine>-Dstdout.encoding=UTF-8 -Dfile.encoding=UTF-8</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regenerates every file in output/. 06 (timings) drifts between runs: the figures are indicative.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
mvn -q -B compile
|
||||
mkdir -p output
|
||||
run() { java -Dstdout.encoding=UTF-8 -cp target/classes "com.ankurm.random.$1" 2>&1 | grep -v -e '^Picked up JAVA_TOOL_OPTIONS' -e '^Picked up _JAVA_OPTIONS' > "output/$2.txt"; }
|
||||
run SeedDemo 01-seeds-and-predictability
|
||||
run RangeDemo 02-ranges-and-bias
|
||||
run ThreadLocalDemo 03-threadlocalrandom
|
||||
run SecureRandomDemo 04-securerandom
|
||||
run RandomGeneratorDemo 05-randomgenerator
|
||||
run BenchmarkDemo 06-timings
|
||||
mvn -B test 2>&1 | grep -E 'Tests run|BUILD|ERROR|FAIL' | grep -v 'Picked up' > output/07-tests.txt
|
||||
echo "regenerated:"; ls output
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run one demo: scripts/run.sh SeedDemo
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
mvn -q -B compile
|
||||
java -Dstdout.encoding=UTF-8 -cp target/classes "com.ankurm.random.${1:?demo class name}"
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.ankurm.random;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Random;
|
||||
import java.util.SplittableRandom;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.random.RandomGenerator;
|
||||
import java.util.random.RandomGeneratorFactory;
|
||||
|
||||
/**
|
||||
* Indicative timings. This is a plain timing loop with a warm-up, NOT a JMH benchmark: use the
|
||||
* ratios, not the absolute numbers, and expect them to move between runs and machines.
|
||||
*/
|
||||
public class BenchmarkDemo {
|
||||
private static final int SINGLE_CALLS = 20_000_000;
|
||||
private static final int THREADS = 4;
|
||||
private static final int CALLS_PER_THREAD = 5_000_000;
|
||||
|
||||
static volatile long sink;
|
||||
|
||||
interface IntSource { int next(); }
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
System.out.println("cores available: " + Runtime.getRuntime().availableProcessors());
|
||||
|
||||
Util.section("One thread: nanoseconds per nextInt(), " + SINGLE_CALLS + " calls");
|
||||
single("Random", new Random()::nextInt);
|
||||
single("SplittableRandom", new SplittableRandom()::nextInt);
|
||||
single("ThreadLocalRandom", () -> ThreadLocalRandom.current().nextInt());
|
||||
single("L32X64MixRandom (default)", RandomGenerator.getDefault()::nextInt);
|
||||
single("Xoshiro256PlusPlus", RandomGeneratorFactory.of("Xoshiro256PlusPlus").create()::nextInt);
|
||||
single("SecureRandom", new SecureRandom()::nextInt);
|
||||
|
||||
Util.section(THREADS + " threads sharing ONE instance, " + CALLS_PER_THREAD + " calls each (wall time, ms)");
|
||||
shared("Random (shared)", new Random()::nextInt);
|
||||
shared("SecureRandom (shared)", new SecureRandom()::nextInt);
|
||||
shared("ThreadLocalRandom.current()", () -> ThreadLocalRandom.current().nextInt());
|
||||
System.out.println("checksum (ignore): " + sink);
|
||||
}
|
||||
|
||||
private static void single(String name, IntSource s) {
|
||||
run(s, 2_000_000); // warm-up
|
||||
long t0 = System.nanoTime();
|
||||
long acc = run(s, SINGLE_CALLS);
|
||||
long t1 = System.nanoTime();
|
||||
sink += acc;
|
||||
System.out.printf("%-28s %7.1f ns/op%n", name, (double) (t1 - t0) / SINGLE_CALLS);
|
||||
}
|
||||
|
||||
private static long run(IntSource s, int n) {
|
||||
long acc = 0;
|
||||
for (int i = 0; i < n; i++) acc += s.next();
|
||||
return acc;
|
||||
}
|
||||
|
||||
private static void shared(String name, IntSource s) throws Exception {
|
||||
run(s, 500_000);
|
||||
Thread[] ts = new Thread[THREADS];
|
||||
long t0 = System.nanoTime();
|
||||
for (int i = 0; i < THREADS; i++) {
|
||||
ts[i] = new Thread(() -> sink += run(s, CALLS_PER_THREAD));
|
||||
ts[i].start();
|
||||
}
|
||||
for (Thread t : ts) t.join();
|
||||
long t1 = System.nanoTime();
|
||||
System.out.printf("%-28s %7.0f ms%n", name, (t1 - t0) / 1e6);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.ankurm.random;
|
||||
|
||||
/**
|
||||
* Shows why java.util.Random must never produce secrets.
|
||||
*
|
||||
* Random is a 48-bit linear congruential generator. nextInt() returns the top 32 bits of the
|
||||
* state, so one output hides only 16 bits. Two consecutive outputs leave 65,536 candidates for
|
||||
* the hidden bits, and the second output rules out all but one of them.
|
||||
*/
|
||||
final class Predictor {
|
||||
private static final long MULT = 0x5DEECE66DL;
|
||||
private static final long ADD = 0xBL;
|
||||
private static final long MASK = (1L << 48) - 1;
|
||||
|
||||
private Predictor() {}
|
||||
|
||||
private static long step(long state) {
|
||||
return (state * MULT + ADD) & MASK;
|
||||
}
|
||||
|
||||
/** Given two consecutive nextInt() results, returns the third one. */
|
||||
static int predictThird(int first, int second) {
|
||||
for (long low = 0; low < (1L << 16); low++) {
|
||||
long state1 = ((first & 0xFFFFFFFFL) << 16) | low;
|
||||
long state2 = step(state1);
|
||||
if ((int) (state2 >>> 16) == second) {
|
||||
return (int) (step(state2) >>> 16);
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("no matching state: not a java.util.Random sequence");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.ankurm.random;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Random;
|
||||
import java.util.SplittableRandom;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.random.RandomGenerator;
|
||||
import java.util.random.RandomGenerator.JumpableGenerator;
|
||||
import java.util.random.RandomGenerator.SplittableGenerator;
|
||||
import java.util.random.RandomGeneratorFactory;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
/** The java.util.random package (JEP 356): the interface, the default, the algorithm catalogue. */
|
||||
public class RandomGeneratorDemo {
|
||||
/** Written against the interface, so it works with any generator. */
|
||||
static int rollDie(RandomGenerator g) {
|
||||
return g.nextInt(1, 7);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Util.section("The old classes already implement RandomGenerator");
|
||||
RandomGenerator[] old = { new Random(), new SecureRandom(), new SplittableRandom(), ThreadLocalRandom.current() };
|
||||
for (RandomGenerator g : old) {
|
||||
int die = rollDie(g);
|
||||
System.out.println(g.getClass().getSimpleName() + " -> rollDie in 1..6: " + (die >= 1 && die <= 6));
|
||||
}
|
||||
|
||||
Util.section("The default generator");
|
||||
System.out.println("RandomGenerator.getDefault() : " + RandomGenerator.getDefault().getClass().getName());
|
||||
System.out.println("RandomGeneratorFactory.getDefault() : " + RandomGeneratorFactory.getDefault().name());
|
||||
|
||||
Util.section("Every algorithm this JDK ships (name, group, state bits, jumpable, splittable)");
|
||||
RandomGeneratorFactory.all()
|
||||
.sorted((p, q) -> p.name().compareTo(q.name()))
|
||||
.forEach(f -> System.out.printf("%-22s %-10s %5d bits jumpable=%-5b splittable=%b%n",
|
||||
f.name(), f.group(), f.stateBits(), f.isJumpable(), f.isSplittable()));
|
||||
|
||||
Util.section("Pick an algorithm by name, and seed it");
|
||||
RandomGenerator g1 = RandomGeneratorFactory.of("Xoshiro256PlusPlus").create(42L);
|
||||
RandomGenerator g2 = RandomGeneratorFactory.of("Xoshiro256PlusPlus").create(42L);
|
||||
System.out.println("Xoshiro256PlusPlus seed 42 #1: " + g1.nextInt(1000) + " " + g1.nextInt(1000) + " " + g1.nextInt(1000));
|
||||
System.out.println("Xoshiro256PlusPlus seed 42 #2: " + g2.nextInt(1000) + " " + g2.nextInt(1000) + " " + g2.nextInt(1000));
|
||||
RandomGenerator l = RandomGenerator.of("L64X128MixRandom");
|
||||
System.out.println("RandomGenerator.of(\"L64X128MixRandom\") -> " + l.getClass().getSimpleName());
|
||||
|
||||
Util.section("Splittable: independent generators for parallel work");
|
||||
SplittableGenerator root = RandomGeneratorFactory.<SplittableGenerator>of("L64X128MixRandom").create(42L);
|
||||
String firsts = IntStream.range(0, 4)
|
||||
.mapToObj(i -> String.valueOf(root.split().nextInt(1000)))
|
||||
.collect(Collectors.joining(" "));
|
||||
System.out.println("first draw of 4 split children: " + firsts);
|
||||
|
||||
Util.section("Jumpable: provably non-overlapping streams");
|
||||
JumpableGenerator j = RandomGeneratorFactory.<JumpableGenerator>of("Xoshiro256PlusPlus").create(42L);
|
||||
System.out.println("jump distance : " + j.jumpDistance());
|
||||
System.out.println("leap distance : " + ((RandomGenerator.LeapableGenerator) j).leapDistance());
|
||||
JumpableGenerator copy = j.copy();
|
||||
copy.jump();
|
||||
System.out.println("original next: " + j.nextInt(1000));
|
||||
System.out.println("after jump next: " + copy.nextInt(1000));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.ankurm.random;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
|
||||
/** Getting a number in a range: the right calls, and the classic wrong ones. */
|
||||
public class RangeDemo {
|
||||
public static void main(String[] args) {
|
||||
Random r = new Random(1);
|
||||
|
||||
Util.section("The right calls (upper bound is always exclusive)");
|
||||
System.out.println("nextInt(10) 0..9 : " + r.nextInt(10));
|
||||
System.out.println("nextInt(1, 7) 1..6 : " + r.nextInt(1, 7));
|
||||
System.out.println("nextInt(-5, 6) -5..5 : " + r.nextInt(-5, 6));
|
||||
System.out.println("nextDouble() [0,1) : " + r.nextDouble());
|
||||
System.out.println("nextDouble(2, 3) [2,3) : " + r.nextDouble(2, 3));
|
||||
System.out.println("ints(5, 1, 7) : " + Arrays.toString(r.ints(5, 1, 7).toArray()));
|
||||
|
||||
Util.section("Bad arguments fail loudly");
|
||||
try { r.nextInt(0); } catch (IllegalArgumentException e) { System.out.println("nextInt(0) -> " + e.getMessage()); }
|
||||
try { r.nextInt(5, 5); } catch (IllegalArgumentException e) { System.out.println("nextInt(5, 5) -> " + e.getMessage()); }
|
||||
|
||||
Util.section("Trap 1: nextInt() % n can be negative");
|
||||
Random t = new Random(2);
|
||||
int negatives = 0;
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
if (t.nextInt() % 6 < 0) negatives++;
|
||||
}
|
||||
System.out.println("1000 draws of nextInt() % 6, negative results: " + negatives);
|
||||
|
||||
Util.section("Trap 2: Math.abs(Integer.MIN_VALUE) is still negative");
|
||||
System.out.println("Math.abs(Integer.MIN_VALUE) = " + Math.abs(Integer.MIN_VALUE));
|
||||
System.out.println("Math.abs(Integer.MIN_VALUE) % 10 = " + (Math.abs(Integer.MIN_VALUE) % 10));
|
||||
System.out.println("(nextInt() hits MIN_VALUE once in 2^32 calls, so tests never catch it)");
|
||||
|
||||
Util.section("Trap 3: modulo bias");
|
||||
int[] counts = new int[3];
|
||||
for (int v = 0; v < 8; v++) counts[v % 3]++;
|
||||
System.out.println("3 random bits (0..7) % 3 -> counts of 0,1,2: " + Arrays.toString(counts));
|
||||
|
||||
int bound = 1_500_000_000;
|
||||
int low = Integer.MAX_VALUE - bound + 1; // values below this are hit twice by (x % bound)
|
||||
double uniformShare = (double) low / bound;
|
||||
int draws = 2_000_000;
|
||||
Random m = new Random(3);
|
||||
int biasedLow = 0, fairLow = 0;
|
||||
for (int i = 0; i < draws; i++) {
|
||||
if ((m.nextInt() >>> 1) % bound < low) biasedLow++;
|
||||
if (m.nextInt(bound) < low) fairLow++;
|
||||
}
|
||||
System.out.printf("bound = %,d, results below %,d%n", bound, low);
|
||||
System.out.printf("expected share if uniform : %.4f%n", uniformShare);
|
||||
System.out.printf("(nextInt() >>> 1) %% bound : %.4f%n", (double) biasedLow / draws);
|
||||
System.out.printf("nextInt(bound) : %.4f%n", (double) fairLow / draws);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.ankurm.random;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.security.Security;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.TreeSet;
|
||||
|
||||
/** SecureRandom: which algorithm you really get, tokens, and what seeding does (and does not) do. */
|
||||
public class SecureRandomDemo {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Util.section("What new SecureRandom() gives you on this machine");
|
||||
SecureRandom sr = new SecureRandom();
|
||||
System.out.println("algorithm : " + sr.getAlgorithm());
|
||||
System.out.println("provider : " + sr.getProvider().getName());
|
||||
|
||||
Util.section("getInstanceStrong()");
|
||||
SecureRandom strong = SecureRandom.getInstanceStrong();
|
||||
System.out.println("algorithm : " + strong.getAlgorithm());
|
||||
System.out.println("securerandom.strongAlgorithms = " + Security.getProperty("securerandom.strongAlgorithms"));
|
||||
|
||||
Util.section("SecureRandom algorithms registered in this JDK");
|
||||
TreeSet<String> names = new TreeSet<>();
|
||||
for (var p : Security.getProviders()) {
|
||||
for (var s : p.getServices()) {
|
||||
if (s.getType().equals("SecureRandom")) names.add(s.getAlgorithm() + " (" + p.getName() + ")");
|
||||
}
|
||||
}
|
||||
names.forEach(n -> System.out.println(" " + n));
|
||||
|
||||
Util.section("A session token: 32 random bytes = 256 bits");
|
||||
byte[] bytes = new byte[32];
|
||||
sr.nextBytes(bytes);
|
||||
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
System.out.println("length in characters: " + token.length() + " (value differs on every run)");
|
||||
|
||||
Util.section("Seeding: SHA1PRNG is deterministic, the default is not");
|
||||
SecureRandom s1 = SecureRandom.getInstance("SHA1PRNG");
|
||||
SecureRandom s2 = SecureRandom.getInstance("SHA1PRNG");
|
||||
s1.setSeed(42L);
|
||||
s2.setSeed(42L);
|
||||
byte[] x = new byte[8], y = new byte[8];
|
||||
s1.nextBytes(x);
|
||||
s2.nextBytes(y);
|
||||
System.out.println("SHA1PRNG, same seed, same bytes: " + Arrays.equals(x, y));
|
||||
|
||||
SecureRandom d1 = new SecureRandom();
|
||||
SecureRandom d2 = new SecureRandom();
|
||||
d1.setSeed(42L);
|
||||
d2.setSeed(42L);
|
||||
d1.nextBytes(x);
|
||||
d2.nextBytes(y);
|
||||
System.out.println(sr.getAlgorithm() + ", same seed, same bytes: " + Arrays.equals(x, y)
|
||||
+ " (setSeed only adds entropy; it does not make the output repeatable)");
|
||||
|
||||
Util.section("It is also a RandomGenerator, so the range methods work");
|
||||
System.out.println("nextInt(1, 7) in 1..6: " + (sr.nextInt(1, 7) >= 1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.ankurm.random;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
/** What a seed is, what it gives you, and why java.util.Random is predictable. */
|
||||
public class SeedDemo {
|
||||
public static void main(String[] args) {
|
||||
Util.section("Same seed, same sequence");
|
||||
Random a = new Random(42);
|
||||
Random b = new Random(42);
|
||||
System.out.println("Random(42) #1: " + a.nextInt(100) + " " + a.nextInt(100) + " " + a.nextInt(100) + " " + a.nextInt(100) + " " + a.nextInt(100));
|
||||
System.out.println("Random(42) #2: " + b.nextInt(100) + " " + b.nextInt(100) + " " + b.nextInt(100) + " " + b.nextInt(100) + " " + b.nextInt(100));
|
||||
|
||||
Util.section("No seed: every instance starts somewhere different");
|
||||
Random c = new Random();
|
||||
Random d = new Random();
|
||||
System.out.println("new Random() #1: " + c.nextInt(100) + " " + c.nextInt(100) + " " + c.nextInt(100));
|
||||
System.out.println("new Random() #2: " + d.nextInt(100) + " " + d.nextInt(100) + " " + d.nextInt(100));
|
||||
System.out.println("(these two lines differ on every run)");
|
||||
|
||||
Util.section("setSeed rewinds an existing instance");
|
||||
Random e = new Random(7);
|
||||
int first = e.nextInt(1000);
|
||||
e.nextInt(1000);
|
||||
e.setSeed(7);
|
||||
System.out.println("first draw before setSeed(7): " + first + ", first draw after: " + e.nextInt(1000));
|
||||
|
||||
Util.section("Two outputs of an unseeded Random predict the third");
|
||||
Random victim = new Random();
|
||||
int o1 = victim.nextInt();
|
||||
int o2 = victim.nextInt();
|
||||
int predicted = Predictor.predictThird(o1, o2);
|
||||
int actual = victim.nextInt();
|
||||
System.out.println("seen output 1 : " + o1);
|
||||
System.out.println("seen output 2 : " + o2);
|
||||
System.out.println("predicted 3 : " + predicted);
|
||||
System.out.println("actual 3 : " + actual);
|
||||
System.out.println("prediction correct: " + (predicted == actual));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.ankurm.random;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
/** ThreadLocalRandom: how to call it, what it refuses to do, and that threads get different streams. */
|
||||
public class ThreadLocalDemo {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Util.section("The one correct way to call it");
|
||||
System.out.println("ThreadLocalRandom.current().nextInt(1, 7) -> in 1..6: "
|
||||
+ inRange(ThreadLocalRandom.current().nextInt(1, 7), 1, 6));
|
||||
|
||||
Util.section("It cannot be seeded");
|
||||
try {
|
||||
ThreadLocalRandom.current().setSeed(42);
|
||||
} catch (UnsupportedOperationException e) {
|
||||
System.out.println("setSeed(42) -> UnsupportedOperationException, message: " + e.getMessage());
|
||||
}
|
||||
|
||||
Util.section("Each thread has its own state");
|
||||
Set<Long> firstValues = new HashSet<>();
|
||||
Thread[] threads = new Thread[4];
|
||||
long[] results = new long[4];
|
||||
for (int i = 0; i < threads.length; i++) {
|
||||
int slot = i;
|
||||
threads[i] = new Thread(() -> results[slot] = ThreadLocalRandom.current().nextLong());
|
||||
threads[i].start();
|
||||
}
|
||||
for (Thread t : threads) t.join();
|
||||
for (long v : results) firstValues.add(v);
|
||||
System.out.println("4 threads, distinct first values: " + firstValues.size() + " of 4");
|
||||
|
||||
Util.section("Works the same on virtual threads");
|
||||
long[] vt = new long[1];
|
||||
Thread.ofVirtual().start(() -> vt[0] = ThreadLocalRandom.current().nextInt(1, 7)).join();
|
||||
System.out.println("virtual thread rolled a die: " + inRange((int) vt[0], 1, 6));
|
||||
}
|
||||
|
||||
private static boolean inRange(int v, int lo, int hi) {
|
||||
return v >= lo && v <= hi;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.ankurm.random;
|
||||
|
||||
/** Tiny printing helper shared by the demos. */
|
||||
final class Util {
|
||||
private Util() {}
|
||||
|
||||
static void section(String title) {
|
||||
System.out.println();
|
||||
System.out.println("== " + title + " ==");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.ankurm.random;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
import java.util.SplittableRandom;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.random.RandomGenerator;
|
||||
import java.util.random.RandomGeneratorFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Pins every claim the post makes about the four APIs. */
|
||||
class RandomContractTest {
|
||||
|
||||
@Test
|
||||
void sameSeedGivesSameSequence() {
|
||||
Random a = new Random(42), b = new Random(42);
|
||||
for (int i = 0; i < 100; i++) assertEquals(a.nextInt(100), b.nextInt(100));
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstThreeDrawsForSeed42AreStable() {
|
||||
Random r = new Random(42);
|
||||
assertArrayEquals(new int[] {30, 63, 48}, new int[] {r.nextInt(100), r.nextInt(100), r.nextInt(100)});
|
||||
}
|
||||
|
||||
@Test
|
||||
void setSeedRewinds() {
|
||||
Random r = new Random(7);
|
||||
int first = r.nextInt(1000);
|
||||
r.nextInt(1000);
|
||||
r.setSeed(7);
|
||||
assertEquals(first, r.nextInt(1000));
|
||||
}
|
||||
|
||||
@Test
|
||||
void twoOutputsPredictTheThirdForJavaUtilRandom() {
|
||||
for (int i = 0; i < 20; i++) {
|
||||
Random victim = new Random();
|
||||
int o1 = victim.nextInt(), o2 = victim.nextInt();
|
||||
assertEquals(victim.nextInt(), Predictor.predictThird(o1, o2));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void predictorCannotPredictSecureRandom() {
|
||||
SecureRandom sr = new SecureRandom();
|
||||
int wrong = 0;
|
||||
for (int i = 0; i < 20; i++) {
|
||||
int o1 = sr.nextInt(), o2 = sr.nextInt(), o3 = sr.nextInt();
|
||||
try {
|
||||
if (Predictor.predictThird(o1, o2) != o3) wrong++;
|
||||
} catch (IllegalStateException noMatch) {
|
||||
wrong++;
|
||||
}
|
||||
}
|
||||
assertEquals(20, wrong);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nextIntModuloCanBeNegative() {
|
||||
Random r = new Random(2);
|
||||
boolean sawNegative = false;
|
||||
for (int i = 0; i < 1000; i++) sawNegative |= r.nextInt() % 6 < 0;
|
||||
assertTrue(sawNegative);
|
||||
}
|
||||
|
||||
@Test
|
||||
void absOfMinValueIsStillNegative() {
|
||||
assertEquals(Integer.MIN_VALUE, Math.abs(Integer.MIN_VALUE));
|
||||
assertTrue(Math.abs(Integer.MIN_VALUE) % 10 < 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void moduloIsBiasedAndNextIntBoundIsNot() {
|
||||
int bound = 1_500_000_000;
|
||||
int low = Integer.MAX_VALUE - bound + 1;
|
||||
double uniform = (double) low / bound;
|
||||
Random m = new Random(3);
|
||||
int draws = 1_000_000, biased = 0, fair = 0;
|
||||
for (int i = 0; i < draws; i++) {
|
||||
if ((m.nextInt() >>> 1) % bound < low) biased++;
|
||||
if (m.nextInt(bound) < low) fair++;
|
||||
}
|
||||
assertEquals(uniform, (double) fair / draws, 0.005);
|
||||
assertTrue((double) biased / draws > uniform + 0.15);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rangeCallsRespectBounds() {
|
||||
Random r = new Random();
|
||||
for (int i = 0; i < 10_000; i++) {
|
||||
int v = r.nextInt(1, 7);
|
||||
assertTrue(v >= 1 && v <= 6);
|
||||
double d = r.nextDouble(2, 3);
|
||||
assertTrue(d >= 2 && d < 3);
|
||||
}
|
||||
assertThrows(IllegalArgumentException.class, () -> r.nextInt(0));
|
||||
assertThrows(IllegalArgumentException.class, () -> r.nextInt(5, 5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void threadLocalRandomRefusesToBeSeeded() {
|
||||
assertThrows(UnsupportedOperationException.class, () -> ThreadLocalRandom.current().setSeed(42));
|
||||
}
|
||||
|
||||
@Test
|
||||
void secureRandomSetSeedDoesNotMakeNativePrngRepeatable() throws Exception {
|
||||
SecureRandom a = new SecureRandom(), b = new SecureRandom();
|
||||
assumeTrue(a.getAlgorithm().startsWith("NativePRNG"), "only meaningful where the default is NativePRNG");
|
||||
a.setSeed(42L);
|
||||
b.setSeed(42L);
|
||||
byte[] x = new byte[16], y = new byte[16];
|
||||
a.nextBytes(x);
|
||||
b.nextBytes(y);
|
||||
assertFalse(Arrays.equals(x, y));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sha1PrngIsRepeatableWhenSeededBeforeFirstUse() throws Exception {
|
||||
SecureRandom a = SecureRandom.getInstance("SHA1PRNG"), b = SecureRandom.getInstance("SHA1PRNG");
|
||||
a.setSeed(42L);
|
||||
b.setSeed(42L);
|
||||
byte[] x = new byte[16], y = new byte[16];
|
||||
a.nextBytes(x);
|
||||
b.nextBytes(y);
|
||||
assertArrayEquals(x, y);
|
||||
}
|
||||
|
||||
@Test
|
||||
void allFourClassicApisAreRandomGenerators() {
|
||||
RandomGenerator[] gs = { new Random(), new SecureRandom(), new SplittableRandom(), ThreadLocalRandom.current() };
|
||||
for (RandomGenerator g : gs) {
|
||||
int v = g.nextInt(1, 7);
|
||||
assertTrue(v >= 1 && v <= 6, g.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultGeneratorIsL32X64MixRandom() {
|
||||
assertEquals("L32X64MixRandom", RandomGeneratorFactory.getDefault().name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void namedAlgorithmWithSameSeedRepeats() {
|
||||
RandomGenerator a = RandomGeneratorFactory.of("Xoshiro256PlusPlus").create(42L);
|
||||
RandomGenerator b = RandomGeneratorFactory.of("Xoshiro256PlusPlus").create(42L);
|
||||
for (int i = 0; i < 100; i++) assertEquals(a.nextLong(), b.nextLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void catalogueContainsTheExpectedFamilies() {
|
||||
var names = RandomGeneratorFactory.all().map(RandomGeneratorFactory::name).toList();
|
||||
assertTrue(names.containsAll(java.util.List.of("Random", "SecureRandom", "SplittableRandom",
|
||||
"L64X128MixRandom", "Xoshiro256PlusPlus", "Xoroshiro128PlusPlus")));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user