Skip to content

Instantly share code, notes, and snippets.

@kdisneur
Created May 30, 2017 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kdisneur/f64f3cbd15a0128d19e13b4c790d4366 to your computer and use it in GitHub Desktop.
Save kdisneur/f64f3cbd15a0128d19e13b4c790d4366 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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