Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: How does Read Lock work?

I am trying to understand whats the effect of calling EntityManager.lock(entity, LockModeType.READ). The API documentation sounds very confusing for me.

If I have to concurrent threads and Thread 1 calls lock(entity, LockModeType.READ), can Thread 2 still read and write the entity?

What I have learned so far:

The lock type READ in JPA1 is the same as OPTIMISTIC in JPA2. If such a lock is set, the EntityManager checks the version attribute before commiting the transaction, but does not update it. I found an explanation for the OPTIMISTIC lock mode: Link. Search for OPTIMISTIC (READ) LockMode Example. As fas as I understand this, setting a read lock in Thread 1 has no effect on Threads 2 ... n. All other threads can still read and write the entity. But when the transaction in Thread 1 commits and an other Thread has updated the entity, the transaction in Thread 1 is rolled back.

Am I understanding this correct?

like image 675
rubberduck Avatar asked Apr 18 '12 20:04

rubberduck


People also ask

What is Pessimistic_write lock?

PESSIMISTIC_WRITE allows us to obtain an exclusive lock and prevent the data from being read, updated or deleted. PESSIMISTIC_FORCE_INCREMENT works like PESSIMISTIC_WRITE, and it additionally increments a version attribute of a versioned entity.

How can we avoid optimistic locking in JPA?

The OptimisticLockType. NONE disables the default optimistic locking mechanism for the TestEntity . However, that would only be useful if you inherited the @Version property from a base class which is annotated with @MappedSuperclass or @Inheritance .

How do you use optimistic locking JPA?

In order to use optimistic locking, we need to have an entity including a property with @Version annotation. While using it, each transaction that reads data holds the value of the version property. Before the transaction wants to make an update, it checks the version property again.


1 Answers

Read is curently deprecated anyway but just for your understanding:

A READ lock will ensure that the state of the object does not change on commit, because the READ lock allows other transactions to update or delete it then if Thread 1 does some change and then commits it first checks the state (the version) of the entity if it checks, it is commited, if not it is not allowed,

so basicly your understanding is correct.

there is also OPTIMISTIC_READ which is the modern way of using it(aslo there is _WRITE).

UPDATE

Ok this article helped me a lot in understanding hope this helps.

like image 175
engma Avatar answered Oct 23 '22 04:10

engma