JPA: How does Read Lock work?

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

If I have to deal with parallel threads and block level 1 calls (entity, LockModeType.READ), can Thread 2 still read and write the object?

What I have learned so far:

The READ lock type in JPA1 is the same as OPTIMISTIC in JPA2. If this lock is set, EntityManager checks the version attribute before committing the transaction, but does not update it. I found an explanation for the OPTIMISTIC lock mode: Link . Search OPTIMISTIC (READ) LockMode example. Since, as I understand it, setting a read lock in Thread 1 does not affect Threads 2 ... n. All other threads can read and write to the object. But when a transaction in thread 1 completes and another thread updates the entity, the transaction in thread 1 rolls back.

Do I get it right?

+6
source share
1 answer

Reading is not recommended anyway, but for your understanding:

A READ lock ensures that the state of the object will not be changed when it is committed, because a READ lock allows other transactions to update or delete them if, in the event Thread 1 makes some kind of change and then performs it, it first checks the state (version) of the object he checks, he is committed, if he is not allowed,

your understanding is so important.

there is also OPTIMISTIC_READ, which is a modern way of using it (_WRITE also exists).

UPDATE

Well, this article helped me understand that this helps.

+4
source

Source: https://habr.com/ru/post/913574/


All Articles