Random are thread-safe. However, the concurrent use of the same java. util. Random instance across threads is synchronized and as we have found out tends to trigger contention issues affecting performance of the application.
This is due to an implementation detail of Random that does not tolerate multithreaded access (it wasn't designed for it, and the docs explicitly call out that Random should not be used from multiple threads, as they do for most types in the . NET Framework). // over with the new number.
A thread-safe class is a class that guarantees the internal state of the class as well as returned values from methods, are correct while invoked concurrently from multiple threads. The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.
When designing a class that may be used for concurrent programming—that is, a class whose instances may be used by more than one thread at a time—it is imperative that you make sure the class is " thread-safe.” Consider the IntList class of Example 2-7. This class is not thread safe.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With