Is Random class thread safe?

Shcheklein picture Shcheklein · Apr 28, 2011 · Viewed 38.6k times · Source

Is it valid to share one instance of the Random class between multiple threads? And to call nextInt(int) from multiple threads in particular?

Answer

Peter Lawrey picture Peter Lawrey · Apr 28, 2011

It is thread safe in the sense it will still generate random numbers when used by multiple threads.

The Sun/Oracle JVM implementation uses synchronized and AtomicLong as seed to improve consistency across threads. But it doesn't appear to be guarenteed across all platforms in the documentation.

I wouldn't write your program to require such a guarantee, especially as you cannot determine the order in which nextInt() will be called.