Reputation: 9374
I have a simple problem. I have a DB table with some data and sequential numbers. And several nodes pointing to database.
I need every node to guarantee that this and only this node picks one row with minimal sequential number at the moment of time.
What is the best way to do this in hibernate?
The first thing that I've done is to execute query with UPGRADE NOWAIT
clause, and then try to update the row. Otherwise if catching LockAcquisitionException
- retry it with some timeout.
while (retryCount < MAX_RETRY_ATTEMPTS) {
try {
Object obj = session().get(MyObject.class, stringId, LockMode.UPGRADE_NOWAIT);
//Acquire this row somehow
} catch (LockAcquisitionException | OptimisticLockException | StaleObjectStateException e) {
retryCount = handleException(retryCount, e);
}
}
But this way is error prone - how much times should I retry and with which interval? I would rather to find better way with guaranteed sequential lock. But have no idea how to do this.
Upvotes: 0
Views: 84
Reputation: 5502
Consider using LockMode.PESSIMISTIC_FORCE_INCREMENT, and release the lock with transaction commit.
Upvotes: 1