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.