In-depth understanding of optimistic locking and pessimistic locking

original address

Introduced in the locking mechanism of the database, 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 simultaneously access the same data in the database.

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

Whether it is pessimistic locking or optimistic locking, it is a concept defined by people and can be regarded as a kind of thought. In fact, it is not only the concept of optimistic locking and pessimistic locking in relational database systems, such as memcache, hibernate, tair, etc., all have similar concepts.

For different business scenarios, different concurrency control methods should be used. Therefore, do not narrowly understand optimistic concurrency control and pessimistic concurrency control as concepts in DBMS, let alone confuse them with the locking mechanism (row lock, table lock, exclusive lock, shared lock) provided in the data. In fact, in DBMS, pessimistic locking is implemented by using the locking 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 locking", Pessimistic Concurrency
Control, abbreviated "PCC") is a method of concurrency control. It prevents a transaction from modifying data in a way that affects other users. If the operation performed by a transaction applies a lock to a row of data, only when the transaction releases the lock, other transactions can perform operations that conflict with the lock.
Pessimistic concurrency control is primarily used in environments where data contention is high, and where the cost of using locks to protect data in the event of a concurrency conflict is less than the cost of rolling back a transaction.

Pessimistic lock, as its name implies, refers to a conservative attitude (pessimistic) that data is modified by the outside world (including other current transactions in the system, as well as transactions from external systems). Therefore, during the entire data processing process, the Data is locked. The implementation of pessimistic locks often relies on the locking mechanism provided by the database (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 successful, 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.

Using pessimistic locking in MySQL InnoDB

To use pessimistic locking, we must turn off the autocommit attribute of the mysql database, because MySQL uses 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 method of select...for update, so that the pessimistic lock is realized by opening the exclusive lock. At this time, in the t_goods table, the data with the id of 1 is locked by us, and other transactions can only be executed after the transaction is committed. This way we can ensure that the current data will not be modified by other transactions.

We mentioned above that using select...for update will lock the data, but we need to pay attention to some lock levels. MySQL
InnoDB defaults to row-level locks. Row-level locks are all index-based. If an SQL statement does not use an index, it will not use row-level locks, and will use table-level locks to lock the entire table. This needs attention.

Advantages and disadvantages

Pessimistic concurrency control is actually a conservative strategy of "lock first and then access", which provides a guarantee for the security of data processing. However, in terms of efficiency, the locking mechanism will cause additional overhead to the database and increase the chance of deadlocks; in addition, since there will be no conflicts in read-only transaction processing, there is no need to use locks. Doing this It can only increase the system load; it also reduces 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 locking

In relational database management systems, optimistic concurrency control (also known as "optimistic locking", Optimistic Concurrency
Control, abbreviated "OCC") is a method of concurrency control. It assumes that multi-user concurrent transactions will not affect each other during processing, and each transaction can process the part of the data affected by each other without generating locks. Before committing a data update, each transaction checks whether other transactions have modified the data after the transaction has read the data. If other transactions have updates, the committing transaction will be rolled back. Optimistic transaction control was first proposed by Professor HTKung.

Optimistic Locking Compared with pessimistic locking, optimistic locking assumes that data will not cause conflicts in general, so when the data is submitted and updated, the data conflict will be formally detected. If a conflict is found , then let the user return the wrong information, let the user decide what to do.

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

Data version, a version identifier added to the data. When reading the data, the value of the version identifier is read out together, and the version identifier is updated every time the data is updated. When we submit the update, compare the current version information of the corresponding record in the database table with the version ID taken out for the first time. If the current version number of the database table is equal to the version ID value taken out for the first time, update it. , otherwise it is considered to be expired data.

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

Optimistic locking using version numbers

When using a version number, you can specify a version number when data is initialized, and each time the data is updated, a +1 operation is performed on the version number. And determine 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};

Advantages and disadvantages

Optimistic concurrency control believes that the probability of data race between transactions is relatively small, so do it as directly as possible, and do not lock until the time of submission, so there will be no locks and deadlocks. However, if you do this directly, you may encounter unexpected results. For example, two transactions both read a row in the database and write back to the database after modification. At this time, you encounter a problem.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325825915&siteId=291194637