Generating Random Numbers with a Specified Seed

suggest change
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

// Creates a Random instance with a seed of 12345.
Random random = new Random(12345L);

// The current thread's ThreadLocalRandom. Its seed is not settable.
ThreadLocalRandom tlr = ThreadLocalRandom.current();

// Throws UnsupportedOperationException. ThreadLocalRandom.setSeed is unsupported
// once the generator has been initialized, which current() already did.
tlr.setSeed(12345L);

The same seed makes java.util.Random produce the same sequence again. new Random() already chooses a seed that is very likely to differ from other instances. ThreadLocalRandom is initialized with an internally generated seed and rejects setSeed.

System.currentTimeMillis() can repeat when two generators are created in the same millisecond, so it is a weak seed:

Random random = new Random(System.currentTimeMillis());
// Also throws UnsupportedOperationException.
ThreadLocalRandom.current().setSeed(System.currentTimeMillis());

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents