Junior — Middle
How will the database handle the situation if two clients simultaneously purchase the same product, specifically, what will happen to the quantity field in the products table?
sobes.tech AI
Answer from AI
When two clients simultaneously purchase the same product, the behavior of the quantity field in the products table depends on how the database is configured and how the transaction logic is implemented.
Ideally, a record-locking transaction (e.g., SELECT ... FOR UPDATE) is used to prevent race conditions. In this case:
- The first client starts a transaction, locks the product record, checks and decreases
quantity. - The second client attempts to do the same but waits for the lock to be released.
- If after the first purchase,
quantitybecomes less than the required amount for the second, the second operation is rolled back or returns an error.
If there are no locks, a situation may occur where both clients read the same quantity simultaneously and both decrease it, leading to incorrect results (e.g., negative stock).
Example in Java using JDBC and transactions:
connection.setAutoCommit(false);
try {
PreparedStatement stmt = connection.prepareStatement("SELECT quantity FROM products WHERE id = ? FOR UPDATE");
stmt.setInt(1, productId);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
int quantity = rs.getInt("quantity");
if (quantity >= purchaseAmount) {
PreparedStatement updateStmt = connection.prepareStatement("UPDATE products SET quantity = quantity - ? WHERE id = ?");
updateStmt.setInt(1, purchaseAmount);
updateStmt.setInt(2, productId);
updateStmt.executeUpdate();
connection.commit();
} else {
connection.rollback();
throw new RuntimeException("Insufficient stock")
}
}
} catch (SQLException e) {
connection.rollback();
throw e;
} finally {
connection.setAutoCommit(true);
}
Thus, proper transaction and lock management guarantees correct updating of the quantity field during concurrent purchases.