Reputation: 9649
Does the JPA method EntityManager#lock take immediate effect on the in-memory managed entity instances or just route the semantics on-demand to the DB?
Upvotes: 1
Views: 1994
Reputation: 7710
Locking using EntityManager#lock is immediate only if you use one of pessimistic lock types.
Using a pessimistic lock type routes lock instruction to the DB and waits until either lock succeeds or a timeout is reached. Therefore the call is blocking and if not successful, transaction is rolled back.
The immediate effect on in-memory objects is then indirect, but immediate - if lock is not obtained, transaction is rolled back and it is not possible to successfully finish the transaction. It makes no sense to modify entity objects after this, as they will not be persisted. But in theory, it is possible to modify and work with the entity object as with any other plain Java object, provided that you catch LockTimeoutException, but I do not recommend this.
If you use optimistic locking, then from the nature of it, the transaction is rolled back only after a collision is detected. This can happen only at the moment an entity would be persisted into the DB (typically at the end of transaction, but also can happen during intermediate flush). The point of optimistic locking is to deffer locking at a later moment when it is obvious that a collision had occurred.
Very nice documentation about JPA locking mechanism can be found in this Locking in JPA page.
Upvotes: 1