Concurrency Control - optimistic / pessimistic locking

In today's rapid development of Internet, network traffic is becoming increasingly apparent benefits, but high traffic brought about a necessary link is high concurrency, and modern systems for handling concurrent There are a number of ways, such as multi-threading, asynchronous call the core function lock, message queues, etc. this article will talk about two approaches to handling high concurrency, optimistic locking (optimistic locking) and pessimistic locking (pessimistic concurrency Control)

Concurrency issues

In order to cope with concurrency, developers proposed the concept of a transaction in order to complete the operation atomic. But in the course of affairs, the same will create many problems, such as dirty reads, non-repeatable read, phantom read, etc., of course, there are different transaction isolation level to solve the corresponding problem.

Dirty read

Dirty read, refers to the thread A in the modified but not committed by the state of the object O transaction, thread B can obtain the state of the object O has not been modified, this time thread B reads the data is dirty data, according to the dirty data operation, and we can not guarantee its correctness.

As a simple chestnut: A single user at a business platform of a commodity, according to the background of the business logic, the corresponding worker thread will open a transaction, deducting the amount corresponding to the inventory, but at the same time, user B is also orders the same items can be submitted in inventory a user thread before deduction of the transaction to acquire the inventory quantity, after performing a single operation, user B can imagine a series of operations corresponding to the worker thread execution is incorrect .

Non-repeatable read

Non-repeatable read, refers to the thread A in the same transaction twice exactly the same data read operation, access to different data, the reason may be in the process of executing a transaction in thread A, thread B for unified data submitted affairs , resulting in two different data acquisition.

Magic Reading

Phantom reads, and non-repeatable read similar but there are differences within the same transaction multiple query returns a result set is not the same (such as an increase or decrease of rows).

Pessimistic locking

Pessimistic locking, also known as pessimistic concurrency control (PCC), the Java-like lock explicit lock, was called pessimistic locking, because the data is modified to hold pessimistic concurrency control, generally considered to be more chance of being concurrent modification of data large, you need to lock to ensure data consistency changes.

Pessimistic lock Example: Thread A, B concurrent modification data O -> A thread acquired the lock, to modify the data state of the operation -> A thread releases the lock, the thread B to acquire the lock, perform data modify the state of the operation -> thread B releases the lock -> modify the operation is complete

Because the data is explicitly lock, in addition to incur additional costs, but also reduce the processing efficiency and increase the chance of a deadlock. So in the current information system species, rarely re-use pessimistic locking.

Pessimistic locking achieve

Most pessimistic locking implementations are based on the database, namely:

  • Before performing the operation give data plus exclusive lock if the lock fails, as the business requires to wait or throw an exception
  • Perform data modification operations update, released after the transaction is committed automatically lock after lock success
// 开启事务
BEGIN;
// FOR UPDATE 加锁
SELECT amount FROM goods WHERE id = 233 FOR UPDATE;
// 进行数据操作
UPDATE goods SET amount = 15 WHERE id = 233;
// 提交释放锁
COMMIT;
复制代码

FOR UPDATE by establishing an exclusive lock before the transaction commits, we can not operate the operation data to ensure data consistency.

Tip When Mysql data index table to be useful in the Sql, uses row-level locks, other times will lock table level.

Optimistic locking

Optimism optimistic locking, pessimistic locking relative pessimism exists. When optimistic locking assumes that the data generally will not cause conflict, so submit updated data before formal conflict or not the data to detect a conflict if found, then let users return an error message, allowing users to decide how do it.

Optimistic locking Example: A thread, thread B reads the data and operates concurrently -> A thread finish, version detection data, the absence of conflict, commit the transaction -> Thread B to complete the operation, carried out version detection, detection of conflicts, do not submit returns and abnormal

 optimistic concurrency control believe that the probability of data races (data race) between the transaction is relatively small, so as to make direct it, until such time as it submitted to lock

Optimistic locking achieve

The main way to achieve optimistic locking conflict detection, CAS (Compare and swap), CAS is a term optimistic locking technique, when multiple threads attempt to use the CAS simultaneously update the same variable, only one thread can update the values ​​of variables, and other thread failure, failure of the thread will not be suspended, but was told that the competition fails, and you can try again.

Simple optimistic locking achieve:

// 得知amount = 4
SELECT amount FROM goods WHERE id = 233;
UPDATE goods SET amount = 2 WHERE id = 233 AND amount = 4;
复制代码

This completes the unlocked data update, if the same data is updated, inconsistent data, compared with stale data can be re-initiate the request. But this will solve the problem caused by ABA.

ABA problem

A thread ABA question refers to the read data amount value is 4, the correlation operation is started, the thread B while modifying amount of 2, 4 turn amount is modified, this time A thread operation execution is completed, it is determined whether the amount is equal to 4, equal to the update. This time the ABA problem arises, although thread A complete update of the data, but can not guarantee the correctness of the process.

ABA problem solving

In order to confirm the consistent version of the data and once acquired, can increase the Version field, synchronization status update Version field when updating the data, so you can guarantee that data to know whether the version of the same problem.

// amount = 4, version = 1
SELECT amount, version FROM goods WHERE id = 233;
UPDATE goods SET amount = 3, version = 2 WHERE id = 233 AND version = 1;
复制代码

Although the increase in operating version can guarantee a consistent version of the data, but this will cause a lot of data modification fail, this will also reduce the amount of processing efficiency.

Therefore yields the following solution:

// amount = 4
SELECT amount FROM goods WHERE id = 233;
UPDATE goods SET amount = amount - 1 WHERE id = 233 AND amount > 0;
复制代码

That solved the Version field in the table invasion, but also solve the problem of a large number of failed updates.

to sum up

Are not really optimistic locking lock, just a thought concurrency control, the efficiency compared to ordinary lock is higher, but do not have good size limit, it will lead to a large number of business failures. The pessimistic locking can guarantee the consistency of the data, but the efficiency is too low, not recommended.

ps: personal blog address is shawJie.me , from time to time will release some of their experienced, learned, understood, and welcome to sit.

Guess you like

Origin juejin.im/post/5d56ee866fb9a06b2005623a