JPA provides essentially 2 types of locking mechanisms to help synchronize access to entities. Both mechanisms prevent a scenario, where 2 transactions overwrite data of each other without knowing it.
By entity locking, we typically want to prevent following scenario with 2 parallel transactions:
- Adam’s transaction reads data X
- Barbara’s transaction reads data X
- Adam’s transaction modifies data X, and changes it to XA
- Adam’s transaction writes data XA
- Barbara’s transaction modifies data X and changes it to XB
- Barbara’s transaction writes data XB
As a result, changes done by Adam are completely gone and overwritten by Barbara without her even noticing. A scenario like this is sometimes called dirty-read. Obviously, a desired result is that Adam writes XA, and Barbara is forced to review XA changes before writing XB.
Optimistic locking is based on assumption that conflicts are very rare, and if they happen, throwing an error is acceptable and more convenient than preventing them. One of the transactions is allowed to finish correctly, but any other is rolled back with an exception and must be re-executed or discarded.
Optimistic locking is fully controlled by JPA. It requires additional version column in DB tables. It is completely independent of underlying DB engine used to store relational data.
On the other hand there is pessimistic locking. For some, pessimistic locking is considered more natural. When transaction needs to modify an entity, which could be modified in parallel by another transaction, transaction issues a command to lock the entity. All locks are retained until the end of transaction and they are automatically released afterwards.
Optimistic locking requires more setup than pessimistic locking, with version column needed for every entity, but then we do no need to remember issuing locks in the transactions. JPA does all the checks automatically, we only need to handle possible exceptions.
Pessimistic locking uses locking mechanism provided by underlying database to lock existing records in tables. JPA needs to know how to trigger these locks and some databases do not support completely.
Even JPA specification says, that it is not required to provide PESSIMISTIC_READ (as many DBs support only WRITE locks):
It is permissible for an implementation to use
LockModeType.PESSIMISTIC_READwas requested, but not vice versa.
For details of how to use various JPA lock modes to implement both optimistic and pessimistic locking, or even combine them if needed, follow to my other post here: http://lostincoding.blogspot.cz/2015/11/differences-in-jpa-entity-locking-modes.html