Which random?
Choose by what happens if someone could predict the numbers.
| You are making | Use | What it does |
|---|---|---|
| Games, sampling, jitter, shuffles: anything that just needs to look random | CasualRandom |
Fast. Seeded once from the operating system, so every run differs. |
| Tests and simulations that must replay exactly | SeededRandom(seed) |
The same seed gives the same sequence, on every run and every platform. |
| Tokens, session ids, salts, keys: anything someone might try to guess | SecureRandom |
Draws fresh entropy from the operating system on every call. No seed, nothing to replay. |
Never use CasualRandom or SeededRandom for a secret. Both are fast generators whose next
number follows from their state. That is exactly what makes SeededRandom replayable, and exactly
what makes either one guessable. SecureRandom is slower, and it is the only one of the three for
secrets. If the operating system cannot supply entropy, creating one fails with a RandomError
rather than quietly handing you weaker numbers.
All three answer the same questions. nextInt(bound) gives an integer from 0 up to, but not
including, bound. nextFloat() gives a number from 0 up to, but not including, 1.
nextBoolean() and nextUInt128() do what they say. A bound of zero or less is a mistake, and
it fails loudly with a RandomError.
Shuffling takes any of them. Array->shuffle(rng) asks only for something that can draw a
bounded integer, so a shuffle in a test can use a SeededRandom and replay, and the same code in
production can use a CasualRandom.
One generator per thread. A generator changes each time it draws, so it belongs to one thread.
The compiler stops you sharing one with a PARALLEL body; give each thread its own, or move one in.
CLASS Main IMPLEMENTS TaskStarter {
METHOD start() RETURNS STATUS {
// A simulation that must replay: the same seed gives the same rolls every time.
SeededRandom replay := CREATE SeededRandom(42)
int64 roll = replay->nextInt(6) + 1
// A code someone might try to guess: fresh entropy on every draw.
SecureRandom secure := CREATE SecureRandom()
int64 code = secure->nextInt(1000000)
// Everything else: fast, and different on every run.
CasualRandom casual := CREATE CasualRandom()
float64 jitter = casual->nextFloat()
printline(("roll $1, code $2:06d, jitter $3")->format(roll, code, jitter))
RETURN (SUCCESS)
}
}