Optimistic Locker is used in MyBatisPlus

Optimistic Locker is used in MyBatisPlus

The implementation of optimistic locking:

1. During the update operation of MyBatisPlus, the internal query operation will be performed first to obtain the current version such as current version=1

2. When updating, the version will be included in the where conditional sentence, such as where id=2 and version=1

3. When performing the update, set version=vesion+1 where version=1

4. If it has not been updated before, at this time version=1, the where clause condition is established, if it has been updated before, then version=2 at this time, so the where clause condition is not established

乐观锁:1.先查询,获得版本号version比如version=1,然后调用MyBatisPlus中的updateById方法后,会在where的条件后面加上and version=1的条件,所以如果version=1的数据已经更新过了,那么此时version=2,所以where id=2 and version=1这个条件就不成立了,就会更新失败;如果之前没有更新过,那么此时version=1,所以where id=2 and version=1这个条件就成立,此时可以更新。
--A线程
update user set name="kuangshen",version=version+1
where id=2 and version=1
    
--B线程抢先完成,这个时候version=2.会导致A修改失败,因为where条件中的version=1条件条件不再满足
update user set name="kuangshen",version=version+1
where id=2 and version=1

Test the optimistic lock plugin in MyBatisPlus

1. Add the version field to the database

Insert picture description here

2. Entity class plus corresponding fields

Insert picture description here

3. Register the component

That is to write a MyBatisPlus configuration class, inject the OptimisticLockerInterceptor plug-in into the configuration class, as shown below:

Insert picture description here

4. Test

If there is only one update, then the optimistic lock must be able to update successfully, as shown below:

Insert picture description here

Assuming that a thread is inserted in the middle of the update to update the data first, then the update will fail, as shown in the following figure:

Insert picture description here

Insert picture description here

In fact, when updating a row of data, the query is performed first, and then when updating, compare the query results to see if they are consistent. If they are inconsistent, it proves that this row of data has been updated from the query to the update process. After the change, the data can no longer be changed at this time, and the optimistic lock will let its update fail to avoid errors; if it is consistent, it proves that the data has not been updated during the process from query to update. At this time, optimistic lock will let Its update data;

Optimistic and pessimistic locking

Personal summary:

Optimistic locks and pessimistic locks are mainly used to deal with concurrency situations, that is, there are multiple threads. Pessimistic locks means that when a thread is executed, other threads will be in a blocked state. When this thread is executed, other threads Before learning the basics of java, the synchronized keyword is equivalent to a pessimistic lock, so that other threads will not affect the data of this thread. The pessimistic lock uses the lock mechanism of the database itself;

Optimistic locking can be executed by other threads when executing a thread. Optimistic locking does not use the database's own locking mechanism, but based on the data itself to ensure the correctness of the data;

Both optimistic and pessimistic locks can prevent dirty reads, phantom reads, and non-repeatable reads.

Baidu search

One, concurrency control

When there may be concurrency in the program , you need to ensure the accuracy of the data in the concurrency situation, so as to ensure that when the current user and other users operate together, the results obtained are the same as the results when he operates alone. This method is called concurrency control. The purpose of concurrency control is to ensure that the work of one user will not unreasonably affect the work of another user.

Failure to do a good job of concurrency control may cause problems such as dirty reads, phantom reads, and non-repeatable reads .

img

The often-mentioned concurrency control is generally related to the database management system (DBMS). The task of concurrency control in the DBMS is to ensure that when multiple transactions access the same data in the database at the same time, the isolation, consistency and uniformity of the database are not destroyed.

实现并发控制的主要手段大致可以分为乐观并发控制和悲观并发控制两种。
First of all, it must be clear: whether it is pessimistic lock or optimistic lock, it is a concept defined by people and can be considered as a kind of thought. In fact, it is not only the concepts of optimistic and pessimistic locking in relational database systems, but also similar concepts such as hibernate, tair , and memcache. Therefore, optimistic locks, pessimistic locks, and other database locks should not be compared. Optimistic locks are more suitable for more reads and less writes (read more scenarios), and pessimistic locks are more suitable for more writes than read less scenarios (more writes scenarios).

Second, pessimistic lock (Pessimistic Lock)

1️⃣Understand
When you want to modify a piece of data in the database, in order to avoid being modified by others at the same time, the best way is to directly lock the data to prevent concurrency. This method of using the database lock mechanism to lock the data before modifying it and then modify it is called pessimistic concurrency control [Pessimistic Concurrency Control, abbreviated "PCC", also known as "pessimistic lock"].

Pessimistic lock, as its name suggests, has strong exclusive and exclusive characteristics. It refers to a conservative attitude towards data being modified by the outside world (including other current affairs of the system, and transaction processing from external systems). Therefore, in the entire data processing process, the data is locked. The realization of pessimistic locking often relies on the lock mechanism provided by the database (and only the lock mechanism provided by the database layer can truly guarantee the exclusivity of data access, otherwise, even if the locking mechanism is implemented in this system, it cannot be guaranteed that the external system will not be modified. data).

img

It is called pessimistic lock because it is a concurrency control method with a pessimistic attitude towards data modification. Always assume the worst case. Every time you read data, other threads will change the data by default, so you need to perform a lock operation. When other threads want to access the data, they need to block and hang. The realization of pessimistic lock:

  1. Traditional relational databases use this lock mechanism, such as row locks, table locks, etc., read locks, write locks, etc., which are all locked before operations.
  2. Implementation of the synchronized keyword in Java .

2️⃣ Pessimistic locks are mainly divided into shared locks and exclusive locks :

  • Shared locks [shared locks] are also called read locks, or S locks for short. As the name implies, a shared lock means that multiple transactions can share a lock for the same data and can access the data, but can only be read but not modified.
  • Exclusive locks [exclusive locks] are also called write locks, or X locks for short. As the name implies, exclusive locks cannot coexist with other locks. If a transaction acquires an exclusive lock on a data row, other transactions can no longer acquire other locks on the row, including shared locks and exclusive locks, but transactions that acquire exclusive locks can Read and modify data rows.

3️⃣ Description
Pessimistic concurrency control is actually a conservative strategy of "fetching the lock before accessing", which provides a guarantee for the security of data processing. But in terms of efficiency, the mechanism of processing locks will cause additional overhead to the database and increase the chance of deadlocks. In addition, it will reduce parallelism. If a transaction locks a row of data, other transactions must wait for the transaction to complete before processing that row of data.

Three, optimistic locking (Optimistic Locking)

1️⃣Understand that
optimistic locking is relative to pessimistic locking. Optimistic locking assumes that data will not cause conflicts under normal circumstances. Therefore, when the data is submitted and updated, the data will be formally tested for conflicts. If conflicts are found, Then return the wrong information to the user and let the user decide what to do. Optimistic locking is suitable for scenarios with many read operations, which can improve program throughput.

img

The optimistic locking mechanism adopts a more relaxed locking mechanism. Optimistic locking is a relatively pessimistic lock, and it is also a mechanism to avoid data processing errors caused by database phantom reading and excessive business processing time. However, optimistic locking does not deliberately use the database's own locking mechanism, but based on the data itself To ensure the correctness of the data. The realization of optimistic locking:

  1. CAS implementation: The atomic variables under the java.util.concurrent.atomic package in Java use a CAS implementation of optimistic locking.
  2. Version number control: Generally, a data version number version field is added to the data table to indicate the number of times the data has been modified. When the data is modified, the version value will be +1. When thread A wants to update the data value, it will also read the version value while reading the data. When submitting the update, if the version value read just now is equal to the version value in the current database, update it, otherwise try again Update operation until the update is successful.

2️⃣ Description
Optimistic concurrency control believes that the probability of data races between transactions is relatively small, so do it as directly as possible, and do not lock until commit, so no locks and deadlocks will occur.

Four, concrete realization

1️⃣The implementation of
pessimistic locks The realization of pessimistic locks often relies on the lock mechanism provided by the database. In the database, the process of pessimistic locking is as follows:

  1. Before modifying the record, try to add exclusive locks to the record.
  2. If the lock fails, indicating that the record is being modified, the current query may have to wait or throw an exception. The specific response method is determined by the developer according to actual needs.
  3. If the lock is successfully locked, the record can be modified, and the transaction will be unlocked after the transaction is completed.
  4. During this period, if there are other operations that modify the record or add an exclusive lock, it will wait for unlocking or throw an exception directly.

Take the more commonly used MySql Innodb engine as an example to illustrate how to use pessimistic locks in SQL.

To use pessimistic locks, you must turn off the automatic commit property of the MySQL database. Because MySQL uses autocommit mode by default, that is, when an update operation is performed, MySQL will immediately submit the result. (sql statement: set autocommit=0)

Explain the use of the pessimistic lock with the e-commerce order deduction process:

img

Above, before modifying the record with id = 1, lock it first through for update , and then modify it. This is a typical pessimistic locking strategy.

If the code for modifying the inventory above occurs concurrently, only one thread can open the transaction at the same time and obtain the lock with id=1, and other transactions must wait for this transaction to be submitted before execution. This ensures that the current data will not be modified by other transactions.

As mentioned above, using select...for update will lock the data, but you need to pay attention to some lock levels, MySQL InnoDB default row-level lock. Row-level locks are based on indexes. If an SQL statement does not use an index, row-level locks will not be used. Table-level locks will be used to lock the entire table. This requires attention.

2️⃣Optimistic lock implementation乐观锁不需要借助数据库的锁机制。

There are mainly two steps: conflict detection and data update. The more typical is CAS (Compare and Swap).

CAS is to compare and exchange. It is a mechanism to solve the performance loss caused by the use of locks in the multi-threaded parallel situation. The CAS operation contains three operands-memory location (V), expected original value (A) and new value (B). If the value (V) of the memory location matches the expected original value (A), the processor will automatically update the location value to the new value (B). Otherwise, the processor does nothing. In either case, it will return the value of that position before the CAS instruction. CAS effectively stated "I think the position (V) should contain the value (A). If it contains the value, put the new value (B) in this position; otherwise, do not change the position, just tell me the current position Value is enough". In Java, the sun.misc.Unsafe class provides hardware-level atomic operations to implement this CAS. A large number of classes under the java.util.concurrent package use the CAS operation of this Unsafe.java class.

When multiple threads try to use CAS to update the same variable at the same time, only one thread can update the value of the variable, and the other threads fail. The failed thread will not be suspended, but will be told that it failed in this competition. And can try again. For example, the previous inventory deduction problem can be achieved through optimistic locking as follows:

img

Optimistic lock usage

Before updating, first query the current inventory quantity in the inventory table (quantity), and then use the inventory quantity as a modification condition when doing the update. When the update is submitted, the current inventory number of the corresponding record in the database table is compared with the inventory number taken out for the first time. If the current inventory number in the database table is equal to the inventory number taken out for the first time, it will be updated, otherwise Think of it as expired data.

The above update statement has a serious problem, namely the ABA problem :img

  1. For example, thread one takes out the inventory number 3 from the database, and then thread two also takes out the inventory number 3 from the database, and thread two performs some operations and becomes 2.
  2. Then the second thread turns the inventory count to 3 again. At this time, the first thread performs the CAS operation and finds that the database is still 3, and then the first thread succeeds.
  3. Although the CAS operation of thread 1 is successful, it does not mean that the process is no problem.

A better solution is to pass a single version field that can be incremented sequentially. The optimization is as follows:img

Optimistic lock will carry a version number every time it performs a data modification operation. Once the version number is consistent with the version number of the data, the modification operation can be performed and the version number can be +1, otherwise the execution will fail. Because the version number of each operation will increase, there will be no ABA problem. In addition to version, you can also use timestamps, because timestamps naturally increase sequentially.

The above SQL actually has a certain problem, that is, once it encounters high concurrency , only one thread can modify it successfully, then there will be a lot of failures. For e-commerce websites like Taobao, high concurrency is common, and it is obviously unreasonable for users to perceive failure. Therefore, we still have to find a way to reduce the granularity of optimistic locking. A better suggestion is to reduce the intensity of optimistic locking, maximize throughput and improve concurrency! as follows:

img

In the above SQL statement, if the number of orders placed by the user is 1, the quantity - 1 > 0optimistic lock control is performed by the method. In the execution process, the value of quantity will be queried once in an atomic operation, and 1 will be deducted.

The lock granularity control in a high concurrency environment is an important science. Choosing a good lock can greatly increase throughput and performance while ensuring data security.

Guess you like

Origin blog.csdn.net/qq_45950109/article/details/112617266