Video in progress

Strong Middle 🌱 Spring

How does optimistic locking (@Version) work, and when would you choose it?

The entity has a version field; the UPDATE goes out with where id = ? and version = ? and increments the version by one. If someone changed the row earlier, 0 rows are updated and an OptimisticLockingFailureException is thrown.

📖 Answer

@Entity
class Product {
    @Id Long id;
    int stock;
    @Version long version;
}

The SQL Hibernate sends:

update product set stock = ?, version = 8 where id = ? and version = 7

Say two people are taking the last item at the same time. Both read version = 7. The first one updates (version becomes 8), and the second one's UPDATE hits 0 rows, so you get an exception. No lost update.

When the exception comes, you either tell the user "the data changed, refresh the page" (exactly what you want for admin forms), or retry the whole transaction with a fresh read (@Retryable or a loop).

Optimistic locking is good when conflicts are rare: lots of reads, few concurrent writes. If many concurrent writes hit a single row (the stock of a popular product), retries pile up; there a pessimistic lock or an atomic SQL (update ... set stock = stock - 1 where stock > 0) is better.

If you hand the version to the client in a REST API as ETag/If-Match, you catch conflicts at the HTTP level too.