-
-
Save kdisneur/f64f3cbd15a0128d19e13b4c790d4366 to your computer and use it in GitHub Desktop.
Why mutability is a problem?
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.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()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The expected value is 55: