Java 8 added a random number generator called SplittableRandom
which seems to be meant for use with streams. However, it isn't clear how it is better than or more useful than ThreadLocalRandom
. From reading documentation, it seems the algorithm was changed to have better statistical properties. That said, why not call it BetterThreadLocalRandom
and drop the split method? Why would anyone ever call split()
?
The usefulness of SplittableRandom
comes from being a deterministic random number generator. In the case of streams, different threads may use different ThreadLocalRandom
values, leading to different calculations each time. Doug Lea mentions this in passing while introducing the class:
"While the ThreadLocalRandom option is great for many purposes, you wouldn't want to use it in, say, a high-quality Monte Carlo simulation."
If there is an interesting outcome to a simulation, and it depended upon a particular sequence of random numbers, SplittableRandom
let's you repeat it for further analysis.
You are comparing two different things meant to be used in different situations. One can fulfil the role of the other up to a certain extent.
A ThreadLocalRandom
is just an instance of a random generator different for the local thread, a SplittableRandom
is a generator and even a generator of generators since it can be split recursively and provide a new SplittableRandom
.
But a SplittableRandom
has nothing to do with threads since it is meant to provide something able to cooperate friendly with streams in a functional environment.
Providing random data should be thread agnostic, even using parallel()
on streams should be thread agnostic. I wouldn't like to find myself doing ThreadLocalRandom.current()
inside a lambda that is processing a stream, would you?
In addition, an implementation which uses a fixed sized pool of sleeping/waking threads to process a parallel stream would use the same ThreadLocalRandom for multiple entries, this couldn't happen with a SplittableRandom
which is bound to a possible parallel path of processing, not to a specific thread.
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