Is Random class thread safe?
Is it valid to share one instance of the Random
class between multiple threads? And to call nextInt(int)
from multiple threads in particular?
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.
It is thread safe, although it wasn't always.
See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6362070 for more details.
Acording to the Java 6 documentation, Math.random() guarantees it's safe for use by multiple threads. But the Random class does not. I would assume then you'll have to synchronize that yourself.
EDIT:
According to the accepted answer, though, the documentation seems to have changed since Java 7 and the Random class seems to offer that guarantee too.
Yes, Random is thread safe. the nextInt()
method calls the protected next(int)
method which uses AtomicLong seed, nextseed
(atomic long) to generate a next seed. AtomicLong
is used for thread-safety upon seed generation.