pessimistic Lock: (Pessimistic locking):
Assume that the probability of a conflict is relatively high,
Implementation: Try to add an exclusive lock (exclusive locking) to the record before making any changes to it. So other transactions need to wait for the lock to be released if they want to manipulate the record
Features: When concurrency is large, frequent access, long wait time, poor concurrency
Example: Java synchronized,sqlserver page-level lock, Oracle row-level lock
Optimistic Lock: (Optimistic locking)
Hypothesis: The probability of a conflict is relatively low
Implementation: Locks the object when committing changes to the record, and checks the integrity of the data before committing
For example, two transactions A and b exist, and A and B are considered to be two atomic operations.
A:cat C = FindByID (catId);
C.setname ("Newcat");
B:update (c)
Then, before B commits, the C object is locked (there is no lock operation in this code because the lock operation is done by the database before B is committed).
Also, in order to avoid the time between a execution and B before execution, the C object is changed by another thread, so check the consistency of the data before committing.
The consistency of the data can be checked either by a timestamp, or by using a self-growing integer to represent the data version number (for example, @version in Hibernate, Morphia)
If the check data has been changed, you need to go back to step a to rerun the program until the commit is successful. or throw an exception directly, it depends on the strategy of the lock.
This retry is tolerable due to the assumption that the probability of a conflict is low, but if it is high concurrency, it can affect performance.
This type of control is also called optimistic concurrency control (optimistic concurrency controls)
Characteristics:
The object is read and changed without locking, and locks are added before committing the change
Optimistic lock and lock time is shorter than pessimistic lock
Can obtain better concurrent access performance with larger lock granularity
Increases the number of times a concurrent user reads an object (one-step query when checking data consistency)
Concurrency control: (ii) optimistic lock pessimistic lock