What distinguishes optimistic locks from other locks is that competing optimistic locks are at first compatible with each other and do not exclude each other. If there is a lock collision, it will not be verified until later. For the lock owner a lock collision manifests itself in an external change (noticeable by the current lock user) to the lock, whereby the optimistic lock becomes invalidated.
With optimistic locks data is changed in two phases:
1. Check to verify that the optimistic lock can be set, that is, there is no external exclusive lock.
2. Optimistic lock is set
3. Data is read
The lock does not protect against external changes to data, but it does help to identify them.
This phase starts if the data is to be changed. The prerequisite is that the original read data has not been changed. The process steps are:
1. Consistency of read data and optimistic lock is checked.
2. Check to verify that the conversion of the optimistic lock to an exclusive lock will not collide with an existing lock.
3. The change is circulated to other owners of optimistic locks. The change is circulated by invalidating the external optimistic locks.
4. Optimistic lock is converted into an exclusive lock.
5. The change itself is executed and becomes visible to all.
6. The lock is released.
Steps 1-4 must be completed in an atomic flow – this means either all the steps must be carried out, or none at all. Once the data has been changed, in transactions processed by other users phase 2 cannot be continued following phase 1. Instead, a conflict solution strategy must be pursued.
The graphic below shows the process flow:
Possible conflict scenarios:
· The user’s attempt to set the optimistic lock fails, because the object has already been exclusively locked by another owner (or locked non-cumulatively by the same owner). The result is the user cannot access the change mode.
· The optimistic lock has been set, but when the user tries to save the (changed) data, it emerges that another optimistic lock has already been converted into an exclusive lock. In this process the optimistic lock has been removed from this transaction.
· The optimistic lock is still valid, but an external shared lock (S), or an exclusive lock that the user has inherited, exists, which would collide with the O lock when it is converted into an E lock.
For more information about the possible conflict scenarios see Conflicts with Optimistic Locks.