Menu

Optimistic and Pessimistic Locking

Optimistic and Pessimistic Locking

Two Approaches

When two users change the same row at the same time, one change can overwrite the other. Hibernate offers two ways to prevent this.

 

Optimistic

Pessimistic

IdeaAssume conflicts are rare, and detect themLock the row so others must wait
MechanismA version columnDatabase lock, such as select ... for update
BlockingNoneOther transactions wait
Best forMost web applicationsHigh-conflict data, such as balances

Optimistic Locking

Add a @Version field. Hibernate includes the version in every update and increments it. If another transaction changed the row first, the update affects zero rows and Hibernate throws an OptimisticLockException.

Pessimistic Locking

The row is locked when you read it, and the lock is held until the transaction ends.

@Entity
public class Account {
    @Id
    private Long id;
    private BigDecimal balance;

    @Version
    private int version;
}

Account account = session.find(Account.class, 1L, LockModeType.PESSIMISTIC_WRITE);

Code Explanation:

  • @Version enables optimistic locking for Account. Hibernate manages the value, and you should never set it manually.
  • The find() call with PESSIMISTIC_WRITE reads the row and locks it so no other transaction can change it.
  • The lock is released at commit or rollback, so it only works inside a transaction.
  • After an OptimisticLockException, the usual response is to reload the data and retry, or to tell the user that the record has changed.

Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details