Lesson · Randomness
Randomness: seeds, ranges and security
13 min readRandomness
Four generators, two jobs. Reproducible randomness for games, simulations and tests; unpredictable randomness for tokens and secrets. Choosing the wrong one is either a broken test or a security hole.
The four generators and their jobs
Math.random() is a convenience wrapper around one shared Random, returning a double in [0, 1). Random has existed since 1.0: thread-safe, seedable, repeatable. ThreadLocalRandom gives each thread its own state, so parallel code stops fighting over one lock. SecureRandom draws from the operating system and is the only one suitable for anything security-shaped.
The split is not about speed, it is about purpose. Reproducibility (same seed, same sequence) is a feature for tests and simulations and a vulnerability for tokens. Unpredictability is the reverse.
| Source | Use for | Seedable / reproducible |
|---|---|---|
| Math.random() | quick one-offs in demos and toys | no control |
| Random | games, simulations, shuffle with a known seed | yes, new Random(seed) |
| ThreadLocalRandom | fast randomness inside parallel code | no (per-thread state) |
| SecureRandom | tokens, salts, passwords, nonces | unpredictable by design |
Random desk · reproducible or unpredictable
seed replay · one seed, two lanes
Two generators built from the same seed. Nothing drawn yet: the seed is the entire state, and both lanes start identical.
range ruler · seed 42 draws from nextInt(10)
bound is exclusive: nextInt(10) covers 0 through 9, and the first draws from seed 42 are 0, 3, 8. Inclusive top: min + nextInt(max - min + 1). Avoid nextInt() % 6: remainder ranges are not equal.
SecureRandom
OS entropy: earlier outputs say nothing about the next one.
new Random(timeNow) is guessable within hours. Never for anything a stranger could use.
Seeds are the contract
A seed initialises the generator's state, and the same generator with the same seed replays the same sequence. That makes failing tests reproducible: log the seed, replay the run. It also means a seed derived from the current time is guessable by anyone who can guess the time, which is why security never uses the seeded generators.
The modern way to pick an algorithm is RandomGeneratorFactory (Java 17+). Names like L64X128MixRandom and Xoroshiro128PlusPlus select well-tested algorithms with documented properties, and the same name plus seed gives the same stream across JVMs.
new Random(42).nextInt(100) == new Random(42).nextInt(100); // true: replayable RandomGenerator g = RandomGeneratorFactory.of("L64X128MixRandom").create(42);
Ranges: bound is exclusive, and modulo is a trap
nextInt(bound) returns 0 up to but not including bound, so nextInt(10) yields 0 through 9. To hit an arbitrary interval, shift: min + nextInt(max - min + 1). The inclusive upper end lives in your arithmetic, not in the API.
The classic range bug is taking a generator's output modulo the span: random.nextInt() % 6 looks fine but the non-negative int range is not divisible by six, so the low remainders are slightly more likely. nextInt(bound) exists precisely because it distributes uniformly.
rand.nextInt(10); // 0..9, uniform min + rand.nextInt(max - min + 1); // inclusive max: put the +1 in the span rand.nextInt() % 6; // works, slightly biased: avoid
Shuffle, pick and sample
Collections.shuffle(list) shuffles in place with an internal Random; the two-argument form takes your generator, which is what makes a failure reproducible. Picking one element is get(random.nextInt(size)), and removing the result repeatedly is how you build a random sample without repetition.
Collections.shuffle(deck, new Random(42)); // reproducible deal String card = deck.get(random.nextInt(deck.size()));
SecureRandom: unpredictability is the requirement
For tokens, session ids and salts, the attacker's whole job is predicting the next value. SecureRandom gathers entropy from the OS, so observing previous outputs says nothing about the next. Do not treat it as a drop-in everywhere: it is slower and blocks when entropy is scarce.
Generate tokens from random bytes, not from random numbers cast to strings: 16 bytes give 128 bits of entropy, which resists brute force the way 10 digits never can.
byte[] token = new byte[16]; new SecureRandom().nextBytes(token); // 128 bits of unpredictable data
A password reset token built from new Random(timeNow) is guessable within hours. Anything a stranger could use to enter an account needs SecureRandom, full stop.
The modern family (Java 17+)
RandomGenerator is the interface all algorithms implement, and RandomGeneratorFactory discovers the ones available in the JDK. Each algorithm documents its state size, period and whether it is jumpable or splittable, so the choice becomes engineering rather than tradition.
SplittableRandom predates the interface and remains the tool for parallel streams: one seed, split into independent streams for the workers, no contention.
SplittableRandom.split() → independent streams for workers RandomGeneratorFactory.all() → the algorithms this JDK ships
Ask the job, not the habit
Reproducible or unpredictable? That one question picks the generator. Everything else, the ranges, the shuffle, the streams, is arithmetic on top of the answer.
Interview angles
Why is new Random(42) called twice producing the same numbers?+
The seed fully determines the generator's state, and the algorithm is deterministic, so the sequence replays. This makes tests and simulations reproducible, and makes seeded generators unfit for security where unpredictability is the point.
nextInt(10): what range, and how do you include 10?+
0 through 9; the bound is exclusive. For an inclusive interval use min + nextInt(max - min + 1). Putting the +1 in the span is the reliable habit.
Why is random.nextInt() % 6 biased?+
The 2^32 possible ints are not divisible by 6, so remainders 0..3 occur slightly more often than 4..5. nextInt(6) uses rejection sampling to keep the distribution uniform.
When must SecureRandom be used instead of Random?+
Whenever predictability is an attack vector: tokens, session ids, salts, passwords, nonces, keys. Random's seed and state are recoverable from outputs, so its sequence is effectively public.
Random versus ThreadLocalRandom versus SplittableRandom?+
Random is thread-safe but serialises threads on one state; ThreadLocalRandom gives each thread independent state for speed in parallel code; SplittableRandom splits one seed into independent substreams, ideal for parallel streams and fork-join tasks.