Optimistic locking two common implementations

The version number of mechanisms

Typically plus version number field in the data table version, showing the number of times the data is modified. When the data is modified, this field value is incremented by one.

As a simple example: Suppose there is an account information table version field, the current value is 1, and the current account balance (Balance) 100.

  1. Operator A is now ready to be read out (version = 1), and subtracting 50 (100-50) from the account balance;
  2. A process operation of the operator, the operator B also reads the user information (version = 1), and subtracting 20 (100-20) from the account balance;
  3. The operator A complete revision of the data version number plus 1 (version = 2), together with the account after deducting the balance (balance = 50), submitted to the database to complete the update;
  4. Operator B operation is completed, and the version number plus 1 (version = 2) attempting to submit data (balance = 80) to the database, but the database records this time than find the version, the version number of the data filed operator B 2, the current version of the database record is also 2, does not meet the " submit recorded version must be greater than the current version in order to perform the update ," the optimistic locking strategy.

Therefore, the operator B submission was rejected. Thus, to avoid the operator B using modified version = 1 based on the old data, resulting in a final cover operator A possible result of the operation.

CAS algorithm

I.e., compare and swap (compare and swap) is a well-known lock-free algorithms . Variables achieve synchronization between multiple threads without lock program that does not use a lock (no thread is blocked), it is also called non-blocking synchronization (Non-blocking Synchronization). CAS algorithm involves three operands:

  • The need to read and write memory value V
  • Comparing value A
  • B intends to write the new value

If and only if the value is equal to V A, CAS B with a new value by updating the value of V atomic manner, they will not perform any operations ( and swap operation is a native atom ). In general, this is a spin operation , i.e. continuously retries .

Guess you like

Origin www.cnblogs.com/cnndevelop/p/12023623.html
Recommended