Sobes.tech
Senior

Why is SELECT FOR UPDATE needed instead of synchronized? And why pessimistic locking instead of optimistic?

sobes.tech AI

Answer from AI

SELECT FOR UPDATE is used to lock rows in a database at the transaction level to prevent concurrent modifications by other transactions. Unlike synchronized in Java, which locks objects in memory within a single JVM, SELECT FOR UPDATE provides a lock at the database level, which is critical in distributed systems with multiple applications or instances.

Pessimistic locking is applied when the likelihood of conflicts is high and it is important to prevent parallel changes immediately to avoid errors and rollbacks. Optimistic locking is suitable when conflicts are rare, and the system can afford to rollback and retry.

Example of using SELECT FOR UPDATE in JDBC:

String sql = "SELECT balance FROM accounts WHERE id = ? FOR UPDATE";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
    ps.setInt(1, accountId);
    ResultSet rs = ps.executeQuery();
    if (rs.next()) {
        int balance = rs.getInt("balance");
        // update balance
    }
}
// changes are committed in the transaction

Thus, SELECT FOR UPDATE provides reliable locking at the database level, which cannot be achieved solely with synchronized in Java.

Why is SELECT FOR UPDATE needed instead of… - sobes.tech