Create a gist now

Instantly share code, notes, and snippets.

Solving a Parallel Streams Puzzler
import java.util.List;
import java.util.stream.LongStream;
import static java.util.stream.Collectors.toList;
public class ParallelStreamsPuzzler {
public static void main(String[] args) {
List<Transaction> transactions
= LongStream.rangeClosed(0, 1_000)
.mapToObj(Transaction::new)
.collect(toList());
Account myAccount = new Account();
// bug
transactions.parallelStream()
.forEach(myAccount::process);
System.out.println("The total balance is " + myAccount.getAvailableAmount());
}
static class Account {
private long total = 0;
public void process(Transaction transaction) {
add(transaction.getValue());
}
public void add(long amount) {
total += amount;
}
public long getAvailableAmount(){
return total;
}
}
static class Transaction {
private final long value;
public Transaction(long value) {
this.value = value;
}
public long getValue() {
return value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment