Optimism lock

As the name implies, the operation is optimistic that the operation will not cause concurrency problems (no other threads will modify the data) and therefore will not be locked. However, when updating, it will determine whether other threads have modified the data before, which is generally achieved by version number mechanism and CAS algorithm.

Simple understanding: the data here, don’t think too much, although you use, out of the problem calculate me, that operation failed after the transaction rollback, prompt.

Version number mechanism

  • Gets the current when the record is fetchedversion
  • Take this with you when you updateversion
  • When you perform an update,set version = newVersion where version = oldVersion
  • ifversionIf not, update fails

The core SQL:

update table 
set name = 'Aron', version = version + 1 
where id = #{id} and version = #{version};
Copy the code

CAS algorithm

Another technique of optimistic locking is that when multiple threads try to update the same variable using CAS at the same time, only one thread can update the value of the variable, and all the other threads fail. The thread that fails is not suspended, but is informed that it has lost the race and can try again.

CAS

The operation contains three operands:

  • Memory location to read or writeV
  • The expected original value for comparisonA
  • The new value to writeB

If the value of memory location V matches the expected original value A, the processor automatically updates that location value to the new value B. Otherwise the processor does nothing. In either case, it returns the value of that location before the CAS instruction (in some special cases of CAS it will only return whether the CAS was successful, not extract the current value).

CAS effectively says “I think position V should contain the value A; If this value is included, place B in this position; Otherwise, do not change the location, just tell me the current value of the location.” This is actually the same principle as optimistic lock collision check + data update.

Second, pessimistic lock

Always assume the worst-case scenario, and lock every time you fetch data in the belief that some other thread will modify it. Once a lock is placed, only one thread can execute it while different threads are executing at the same time, and the other threads wait at the entrance until the lock is released.

Pessimistic locking is widely used in MySQL and Java

  • MySQLRead lock, write lock, row lock, etc
  • JavathesynchronizedThe keyword

Third, summary

Read more, less likely to conflict, optimistic lock write more, more likely to conflict, pessimistic lock