Students book 2-hour slots on the EdgeCampus GPU server through a web app running on three application servers behind a load balancer, sharing one MySQL database. The booking code is:
// 1. check
int n = jdbc.queryForObject("SELECT COUNT(*) FROM bookings WHERE gpu = ? AND slot = ?", Integer.class, gpu, slot);
if (n == 0) {
// 2. act
jdbc.update("INSERT INTO bookings(gpu, slot, student) VALUES (?, ?, ?)", gpu, slot, student);
}
At 8:00 on Monday, when bookings open, some slots end up booked twice.
- Explain the race with a timeline involving two servers.
- Explain why adding
synchronizedto the Java method does not fix it. - Propose three correct solutions at different levels (database constraint, transaction/locking, distributed lock or queue) and compare them (correctness, performance at 8:00, complexity, failure behaviour).
- How would you test that the fix works?