Skip to content

Instantly share code, notes, and snippets.

@raoulDoc
Created June 13, 2016 21:56
Show Gist options
  • Save raoulDoc/88db7b9be2fd8221f8157a106782deeb to your computer and use it in GitHub Desktop.
Save raoulDoc/88db7b9be2fd8221f8157a106782deeb to your computer and use it in GitHub Desktop.
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