-
-
Save cloudbank/2ef0013fc5337f92bffc5667afa9122a to your computer and use it in GitHub Desktop.
Solving a Parallel Streams Puzzler
This file contains 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.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