4
votes

Background Info: I have an issue that is symptomatic of an entity update not going through. Reviewing my logs, I can see see the update sql statements that I expected, but they are almost simultaneous (0.012 seconds apart) and the application uses a pessimistic read lock when updating the entity.

That leads me to my question: What is the expected behavior when a pessimistic lock exists? Should I still expect to see multiple update queries? I should expect the PessimisticLockException to be thrown, right? Are there any other indicators I should look for?

Hibernate is my JPA implementation.

2

2 Answers

4
votes

Pesimistic locks are actually propagated to the DB level using SQL-queries (check the executed queries to compare). If a pessimistic lock exists, the application should wait for the DB until the lock is released, so it is not mandatory an expcetion to be thrown (but it could be).

Now about the exceptions:

/*
PessimisticLockException if pessimistic locking fails and the transaction is rolled back
LockTimeoutException if pessimistic locking fails and only the statement is rolled back
*/
public <T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode);

For other EntityManager methods those two exceptions are thrown in simmilar situations.

1
votes

Pessimistic locking prevents objects from being updated simultaneously. Instead, the object's updates are forming the sort of chain - if the lock already exists, the update will wait until the lock is released.

Thus, throwing an exception is not expected outcome of pessimistic lock. Expected behavior is eliminating of concurrency I described above.

For further reading you can refer to this and this sources.

In our case it seems that your update is not going through because it is overwritten by some later update.