Last active
March 22, 2016 22:36
-
-
Save Dierk/7ac2ece12e7133bfcf3c to your computer and use it in GitHub Desktop.
adding numbers one to ten can easily lead to random results when done in parallel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Optional; | |
import java.util.concurrent.atomic.AtomicInteger; | |
import java.util.function.Supplier; | |
import java.util.stream.Stream; | |
public class RNG { | |
static Supplier<Integer> countGen(AtomicInteger i) { | |
return (()-> i.getAndIncrement()); | |
} | |
public static void main(String[] args) { | |
final Supplier<Integer> count = countGen(new AtomicInteger(1)); | |
final Optional<Integer> sum = Stream.generate(count).limit(10).parallel().reduce((a, b) -> a + b); | |
System.out.println("sum = " + sum); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The randomness does not come from limit() but from generate() - and I very much agree: this is, just from the method name, quite unexpected. iterate(T seed, UnaryOperator f) would probably be the right choice - at least I then get always the same result (55).
With iterate() there is also no need for AtomicInteger anymore.