Created
June 13, 2016 21:56
-
-
Save raoulDoc/88db7b9be2fd8221f8157a106782deeb 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