Instantly share code, notes, and snippets.

@kdisneur /Main.java Secret
Created May 30, 2017

Embed
What would you like to do?
Why mutability is a problem?
import java.util.ArrayList;
import java.util.List;
class Order {
private int loyaltyPoints;
public Order(int loyaltyPoints) {
this.loyaltyPoints = loyaltyPoints;
}
public int getLoyaltyPoints() {
return this.loyaltyPoints;
}
}
class OrderRepository {
private static List<Order> list = new ArrayList<Order>();
public static void add(Order order) {
list.add(order);
}
public static List<Order> fetchAll(Customer customer) {
return list;
}
}
class Customer {
private String code;
private int loyaltyPoints;
public int getLoyaltyPoints() {
return this.loyaltyPoints;
}
public void computeLoyaltyPoints() {
final List<Order> orders = OrderRepository.fetchAll(this);
this.loyaltyPoints = 0;
for (final Order order : orders) {
this.loyaltyPoints += order.getLoyaltyPoints();
}
}
}
class ComputeFidelityPoints implements Runnable {
private Customer customer;
public ComputeFidelityPoints(Customer customer) {
this.customer = customer;
}
public void run() {
customer.computeLoyaltyPoints();
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
for (int i = 1; i <= 10; i++) {
OrderRepository.add(new Order(i));
}
final Customer customer = new Customer();
Thread thread = new Thread(new ComputeFidelityPoints(customer));
Thread thread2 = new Thread(new ComputeFidelityPoints(customer));
thread.start();
thread2.start();
thread.join();
System.out.println(customer.getLoyaltyPoints());
}
}
@kdisneur

This comment has been minimized.

Owner

kdisneur commented May 30, 2017

The expected value is 55:

$ java Main
100
$ java Main
94
$ java Main
75
$ java Main
58
$ java Main
83
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment