Find the bug · #63 · Caching and state Medium Java
Every customer sees the same cart
Customers see items in their cart that they never added.
On this page
The report
Customers report items in their cart that they never added, and removing them doesn’t help: they come back. Every customer on the server seems to be sharing one cart.
The code
Read it first: what should it do? Then click the line where you think the bug is.
class Cart {
private static final List<String> items = new ArrayList<>();
private final String owner;
Cart(String owner) { this.owner = owner; }
void add(String item) { items.add(item); }
List<String> items() { return List.copyOf(items); }
}Read it, then pick a line.
What does static mean for a field?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
Cart asha = new Cart("asha");
Cart ravi = new Cart("ravi");
asha.add("headphones");
System.out.println("Ravi's cart: " + ravi.items());It prints
Ravi's cart: [headphones]
It should print
Ravi's cart: []
Show the answer: the bug, the fix, and how you’d find it
The bug (line 2)
Line 2 declares items as static. A static field belongs to the class, not to each object, so there is one list shared by every Cart ever created: every customer adds to, and sees, the same items. Each cart needs its own list: drop static.
The fix
1class Cart {2 private static final List<String> items = new ArrayList<>();2 private final List<String> items = new ArrayList<>();3 private final String owner;4 5 Cart(String owner) { this.owner = owner; }How you’d find it
- Reproduce with two carts: add to one, read the other. The item is there.
- Two separate objects sharing data means the data isn’t really in the objects. Look at how
itemsis declared. static: one copy for the whole class.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
Cart a = new Cart("a");
Cart b = new Cart("b");
a.add("pen");
check(b.items().isEmpty(), "carts are separate");
check(a.items().equals(List.of("pen")), "own items kept");Where else this bites
- Spring beans are singletons by default: a field on a service is shared by every request.
- Module-level variables in Node or Python servers (see the next drill).