Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of SplittableRandom?

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()?

like image 676
Carl Mastrangelo Avatar asked Nov 28 '17 02:11

Carl Mastrangelo


2 Answers

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.

like image 60
Carl Mastrangelo Avatar answered Oct 24 '22 19:10

Carl Mastrangelo


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.

like image 22
Jack Avatar answered Oct 24 '22 19:10

Jack