For some reason I used to think that java.util.Random is thread-unsafe, a-la HashMap or BitSet, and Math.random() is implemented either as wrapping access to Random with synchronized block, or ThreadLocalRandom.current().nextDouble().
Actually it turns out that java.util.Random is thread-safe (via atomics). Hence the takeaway: even if I need some random input in a single thread, it makes sense to use ThreadLocalRandom, because there isn't atomic reads and writes inside, compiled as locked instructions and emitting memory barriers.
Moreover, since Java 8, ThreadLocalRandom is essentially a singleton, it's state is kept in some fields of java.lang.Thread class. Therefore method ThreadLocalRandom.current() is not an access to ThreadLocalMap, but just a static field read, i. e. very cheap.
I have two questions:
From Computer Science point of view, is the output of several linear congruential random generators (initialized the way
ThreadLocalRandoms are) is same "random" as an output of the single linear congruential random generator (thejava.util.Randominstance)?If answer to the first question is Yes, is there any reason to write the construction
new Random()(without seed) instead ofThreadLocalRandom.current(), ever?
Aucun commentaire:
Enregistrer un commentaire