Vrishank
Vrishank

Reputation: 364

LockModeType.OPTIMISTIC_FORCE_INCREMENT is this lock taken at application level or database level

In case of hibernate jpa LockModeType.OPTIMISTIC_FORCE_INCREMENT, is this lock taken at application level or database level.

I am using following snippet for taking optimistic locks:

setting = this.entityManager.find(Setting.class, setting.getId(), 
LockModeType.OPTIMISTIC_FORCE_INCREMENT);
setting.setUpdateTimestamp(new Date());
newSettingList.add(setting);

Suppose there are two jvm's running and both have same methods and there is conflict, will this locking mechanism work in this case?

My observation is that, whenever I was debugging and "newSettingList.add(setting);" at this line in code, I was not seeing any changes in database at that point. So how locking is ensured at database level?

Upvotes: 2

Views: 1555

Answers (1)

Ioannis Mitrolios
Ioannis Mitrolios

Reputation: 490

Optimistic Locking is a strategy where you read a record, use version number to check that the version hasn't changed before you write the record back. When you write the record back you filter the update on the version to make sure it's atomic.

Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoid Deadlocks.

Better explanation here.

This means that since you use optimistic locking you don't intervene in the locks at the database level. What you you do is simply use the database to keep versioning of the objects-entities. For example:

a) You open a T1 transaction from the 1st jvm and read an object with version v1.

b) You open a T2 transaction from the 2nd jvm and read the same object with v1.(no update in this object has been made).

c) You update in T1 transaction the object and setting its version v2. you commit the transaction.

d) You try to have access again in db for the object but you get an exception because of the versioning.
But there is no need to have access from the same jvm for the 2 transactions

Upvotes: 1

Related Questions