3

I have two questions regarding the Pessimistic LockModes that are available in Hibernate 3.3.2.ga :

  1. If I lock a set of rows using lockmode UPGRADE, do the locks gets released when you move out of the transaction scope? If yes, can we lock-unlock across transactions?

  2. For the following scenario, which LockMode would be useful

    • Thread 1, tries to obtain a lock and locks a set of rows

    • Thread 2, tries to obtain the lock on the same set of rows (as were locked by Thread 1) at this time thread 2 gets a exception saying that Rows are locked

    Which would be the best pessimistic LockMode?

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911

1 Answers1

6
  1. The LockMode.UPGRADE uses select ... for update, so the locks are held for the whole duration of the current transaction. The only way to release the locks is to either commit or rollback the transaction.

  2. A select ... for update lock will cause the second transaction to wait for the first one to release the locks. If you want to fail fast, you need to use: UPGRADE_NOWAIT, which will use select ... for update no wait query, that throws an exception if the lock cannot be acquired (this is supported by Oracle and PostgreSQL).

  3. Or, you can use the Hibernate LockOptions as follows:

    entityManager
    .unwrap(Session.class)
    .buildLockRequest(
        new LockOptions(LockMode.PESSIMISTIC_WRITE)
        .setTimeOut(LockOptions.NO_WAIT))
    .lock(entity);
    

For more details, check out my Transactions and Concurrency Control presentation from Voxxed Days Zurich.

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • 1
    Thanks Vlad, was trying to implement a Pessimistic lock with no wait condition in MySQL but does not seem possible. Will have to go with optimistic version check strategy. – Deepesh Satija May 25 '15 at 18:18