Categories
hibernate optimistic-locking pessimistic-locking race-condition sql

How does Hibernate do row version check for Optimistic Locking before committing the transaction

When before committing the current transaction hibernate checks the version of the row, it should issue an sql select statement for fetching ithe row.

Assume that after issuing that select statement hibernate finds out that the row version is not changed, hence it should proceed with committing the transaction.

I’m wondering how hibernate can be sure that in time slot between selecting the row and committing the current transaction no any other transaction will update the row changing its version number ? The only possible thing that hibernate can do seems to be the row version selection with pessimistic locking using Select ... For Update or a transaction with such an isolation level which will lock the row that is being read.

If what I am thinking is true:

  • then hibernate optimistic locking does actually use a pessimistic locking for its operation although that pessimistic lock is held for a very short time as the transaction will be committed immediately after that.

  • otherwise we have a short time slot between row version check and a commit, where a race condition can occur.

Please share your thoughts.