简体   繁体   中英

ThreadlocalRandom and just Random

I'm reading a java 8 book by Richard Warburton and have a question about random number genereation for parallel streams. Here's the two-dice-throw simulation example he provided:

public Map<Integer, Double> parallelDiceRolls(){
    double fraction = 1.0/N;
    return IntStream.range(0, N)
                     .parallel()
                     .mapToObj(twoDiceThrows())
                     .collect(groupingby(side -> side, 
                               summingDouble(n -> fracton));

My question is about the twoDiceThrow function. Later on he gives its sketch :

private int twoDiceThrow(ThreadLocalRandom random){
    int firstThrow = random.nextInt(1, 7);
    int secindThrow = random.nextInt(1, 7);
    return firstThrow + secondThrow;
}

The question here is about ThreadLocalRandom . Doesn't it hurt the statistic? I mean ThreadLocalRandom is confined to a Thread and since we process our stream in parallel one thread doing the job knows nothing about results produced by the other. Therefore the statistic might differ from one that would be aggregated with Random and synchronization .

The sequence of values generated from a Random should be uncorrelated.

Similarly the sequence of values generated from a ThreadLocalRandom should be uncorrelated with values from itself, and values from any other ThreadLocalRandom with a different seed.

So switching to ThreadLocalRandom should give values with the same statistics as using Random .

The advantage is that you avoid any need for synchronization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM