multithreading - Java Configuring random number generators in multi-threaded environment -


i have application uses pseudo-random numbers. while i'm testing application, want reproducibility, arrange using seed random number generator. currently, rng declared inside class uses static variable: private static random rng = new random(seed). have few questions.

  1. given want seed rng reproducibility, make sense declare variable static?
  2. i may need add more different classes need random numbers. should move rng separate class can still use 1 seed whole application? if so, should use static random or singleton object?
  3. what happens if decide use random numbers in multiple threads? seems if use strategy 2., might still lose predictability, can't sure order in threads going access rng. rng still generate same, predictable sequence of random numbers, 1 run of program another, thread grabs first (or nth) random number in sequence may differ.
  4. what indicates me each thread needs own rng in order results reproducible across runs. mean each thread needs own seed? if so, guarantee reproducibility, or there else need eliminate randomness may introduced having multiple threads?
  5. is there way generate seeds single number minimizes correlation between different rngs?

in other words, if thread 0 has random thread0rng = new random(seed) , thread 1 has random thread1rng = new random(seed), need 1 seed, random numbers in each thread highly correlated. have 2 seeds, couldn't associate run of program single number, passed on command line, say. possible , appropriate seed0 = somefunction(seed,0) , seed1 = somefunction(seed,1)?

yes, should give each thread own random object avoid unreproducable interleaving due thread timing.

you can seed them same number, exact same sequence of numbers. don't know if that's problem.

if problem, can have 1 "master" random object generate seeds other ones. every time create new thread, seed master. have make sure create threads (or @ least retrieve seeds) in same order every time.