Wednesday, August 12, 2020

Optimistic Vs Pessimistic lock

When you need a lock ?

Let's take an example in any web application where two user simultaneous read the record and both are trying to update the record inside the database in that case last user will win and it will override the first user data. In this case first user data will be lost without any warning / exception.

So to deal with this kind of situation we need 'lock mechanism' .

Optimistic lock:

Optimistic lock don't lock the table while reading so in above example both users can simultaneously read the record but while updating it will check the conflict like if user A first updated the record and then user B try to update the record with their version then application will throw exception. In this case user B need to read again latest record and then can update.

How to implement 'optimistic' lock ?

JPA / Hibernate we can use the concept of 'version'. Inside the entity you need to define version attribute in the following manner.

@Version
private int version;

So when hibernate execute the 'update' query for the entity it will apply version in where clause
in following manner

where version=?
version will contain the old value that entity received while reading if it don't match
at the time of update transaction will fail.

Pessimistic lock:

Pessimistic locking mechanism will be used to prevent the simultaneous update of the record. It is an exclusive lock so that no one else can start modifies the record. The record will be locked as soon as it accessed. In above example if user A start read the record
it will lock the record in table, this will block the other user to read the data as well.

How to implement 'pessimistic' lock using JPA?

Using JPA we can implement pessimistic lock.

LockModeType.PESSIMISTIC_READ and LockModeType.PESSIMISTIC_WRITE


LockModeType.PESSIMISTIC_READ: When you want to read the entity only.

EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); User user = entityManager.find(User.class, 10L, LockModeType.PESSIMISTIC_READ);


LockModeType.PESSIMISTIC_WRITE : When your transaction can update the entity. It is an
exclusive lock prevent other transaction from acquiring READ or WRITE.


EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); User user = entityManger.find(User.class, 10L, LockModeType.PESSIMISTIC_WRITE);








Labels: , , , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home