[Elementary] In-depth understanding of optimistic locking and pessimistic locking

[Elementary] In-depth understanding of optimistic locking and pessimistic locking

As mentioned in the database lock mechanism, the task of concurrency control in the database management system (DBMS) is to ensure that the isolation and unity of the transaction and the unity of the database are not destroyed when multiple transactions access the same data in the database at the same time.

Optimistic concurrency control (optimistic locking) and pessimistic concurrency control (pessimistic locking) are the main technical methods used for concurrency control.

Whether it is pessimistic lock or optimistic lock, it is a concept defined by people and can be regarded 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 memcache, hibernate, and tair.

For different business scenarios, different concurrency control methods should be selected. Therefore, do not narrowly understand optimistic concurrency control and pessimistic concurrency control as concepts in the DBMS, let alone confuse them with the locking mechanisms provided in the data (row locks, table locks, exclusive locks, and shared locks). In fact, in DBMS, pessimistic locking is achieved by using the lock mechanism provided by the database itself.

Let's learn about pessimistic locking and optimistic locking respectively.

Pessimistic lock


In relational database management systems, pessimistic concurrency control (also known as "pessimistic lock", Pessimistic Concurrency Control, abbreviated "PCC") is a method of concurrency control. It can prevent a transaction from modifying data in a way that affects other users. If the operation performed by a transaction is locked for a certain row of data, only when the transaction releases the lock, other transactions can perform operations that conflict with the lock.
Pessimistic concurrency control is mainly used in environments with intense data contention, and in environments where the cost of using locks to protect data when concurrency conflicts occurs is lower than the cost of rolling back transactions.

Pessimistic lock, as its name suggests, it refers to a conservative attitude (pessimistic) about data being modified by the outside world (including other transactions in this system, and transactions from external systems). Therefore, in the entire data processing process, The data is locked. The realization of pessimistic locking often relies on the locking mechanism provided by the database (and only the locking 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)

In the database, the process of pessimistic locking is as follows:

Before modifying any record, try to add exclusive locking to the record.

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.

If the lock is successfully locked, the record can be modified, and the transaction will be unlocked after the transaction is completed.

In the meantime, if there are other operations that modify the record or add an exclusive lock, it will wait for us to unlock it or throw an exception directly.

Pessimistic locking in MySQL InnoDB

To use the pessimistic lock, we must turn off the autocommit attribute of the mysql database, because MySQL uses the autocommit mode by default, that is, when you perform an update operation, MySQL will immediately submit the result. set autocommit=0;

//0.开始事务
begin;/begin work;/start transaction; (三者选一就可以)
//1.查询出商品信息
select status from t_goods where id=1 for update;
//2.根据商品信息生成订单
insert into t_orders (id,goods_id) values (null,1);
//3.修改商品status为2
update t_goods set status=2;
//4.提交事务
commit;/commit work;

In the above query statement, we used the select...for update method, so that the pessimistic lock is realized by opening the exclusive lock. At this time, in the t_goods table, the data with id 1 is locked by us, and other transactions can only be executed after the transaction is committed. In this way we can ensure that the current data will not be modified by other transactions.

As we mentioned above, using select...for update will lock the data, but we 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, and table-level locks will be used to lock the entire table. This requires attention.

Pros and cons

Pessimistic concurrency control is actually a conservative strategy of "fetch locks before access", which provides a guarantee for the security of data processing. But in terms of efficiency, the mechanism of processing locks will cause additional overhead for the database and increase the chance of deadlocks; in addition, because there will be no conflicts in read-only transaction processing, there is no need to use locks. It can only increase the system load; it will also reduce the parallelism. If a transaction locks a row of data, other transactions must wait for the transaction to complete before processing the number of rows

Optimistic lock

In relational database management systems, optimistic concurrency control (also known as "optimistic lock", Optimistic Concurrency Control, abbreviated "OCC") is a method of concurrency control. It assumes that concurrent transactions of multiple users will not affect each other during processing, and each transaction can process the part of the data affected by each without locking. Before committing the data update, each transaction will first check whether other transactions have modified the data after the transaction reads the data. If other transactions are updated, the transaction that is being committed will be rolled back. Optimistic transaction control was first proposed by Professor HTKung.

Optimistic Locking (Optimistic Locking) Relative to pessimistic locking, the assumption of optimistic locking believes that data will not cause conflicts under normal circumstances, so when the data is submitted and updated, it will formally detect whether the data conflicts or not. If a conflict is found , Let the user return wrong information, let the user decide how to do it.

Compared with pessimistic locking, optimistic locking does not use the locking mechanism provided by the database when processing the database. The general way to achieve optimistic locking is to record the data version.

Data version, a version identifier added for data. When reading data, the value of the version identifier is read together, and the version identifier is updated every time the data is updated. When we submit the update, we judge that the current version information of the corresponding record in the database table is compared with the version ID that was fetched for the first time. If the current version number of the database table is equal to the version ID value fetched for the first time, then update , Otherwise it is considered expired data.

There are two ways to implement data version, the first is to use the version number, and the second is to use the timestamp.

Use version numbers to implement optimistic locking

When using a version number, you can specify a version number during data initialization, and perform a +1 operation on the version number every time the data is updated. And judge whether the current version number is the latest version number of the data.


1.查询出商品信息
select (status,status,version) from t_goods where id=#{id}
2.根据商品信息生成订单
3.修改商品status为2
update t_goods 
set status=2,version=version+1
where id=#{id} and version=#{version};

Pros and cons

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. But if you simply do this directly, you may still encounter unexpected results. For example, two transactions read a certain row of the database and write it back to the database after modification. At this time, problems are encountered.
[Elementary] In-depth understanding of optimistic locking and pessimistic locking

The operation performed by the transaction applied a lock to a row of data"

Guess you like

Origin blog.51cto.com/13626762/2545864