Pessimistic locking and optimistic locking in MySQL

Pessimistic locking and optimistic locking in MySQL

In relational databases, pessimistic locking and optimistic locking are solutions to resource concurrency scenarios. Next, we will explain in detail the actual use and advantages and disadvantages of these two concurrency solutions.

First, define the database and make a simple inventory table as follows:

CREATE TABLE `order_stock` (
 `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
 `oid` int(50) NOT NULL COMMENT 'Product ID',
 `quantity` int(20) NOT NULL COMMENT 'Inventory',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

Quantity represents the inventory of different commodity oids. Next, OCC and PCC use this database for demonstration.

Optimistic Locking (OCC)

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 it without generating locks. Before committing data updates, each transaction will first check whether other transactions have modified the data after reading it. If other transactions have updates, the transaction being committed will be rolled back.

That is, "optimistic locking 🔒" believes that the user who takes the lock will most likely succeed, so it is enough to take the lock at the last step of the business operation that actually requires updating the data. This can avoid using the row locks defined by the database itself and avoid deadlocks.

UPDATE order_stock SET quantity = quantity - 1 WHERE oid = 1 AND quantity - 1 > 0;

Optimistic concurrency control is mostly used in environments with little data contention and conflicts. In such environments, the cost of occasionally rolling back a transaction is lower than the cost of locking data when reading it, so higher throughput can be achieved than other concurrency control methods.

Pessimistic locking PCC

It prevents a transaction from modifying data in a way that affects other users. If a transaction performs an operation that reads a row of data and applies a lock, other transactions can only perform operations that conflict with the lock when the transaction releases the lock.

This design adopts the "one lock 🔒 two queries 🔍 three updates" mode, which uses select ... for update keyword in the database to add a row-level lock 🔒 to the current transaction, first lock the data to be operated, and then execute the corresponding query data and perform the update operation.

BEGIN
SELECT quantity FROM order_stock WHERE oid = 1 FOR UPDATE;
UPDATE order_stock SET quantity = 2 WHERE oid = 1; 
COMMIT;

Another problem with MySQL is that all scanned rows will be locked during the execution of the select ... for update statement, which can easily cause problems. Therefore, if you use pessimistic locking in MySQL, make sure to use the index instead of a full table scan.

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 occur is lower than the cost of rolling back transactions.

Advantages and disadvantages of OCC and PCC

OCC Advantages and Disadvantages

【advantage】

  • Optimistic locking believes that the probability of data race between transactions is relatively small, so it is possible to proceed directly and lock only when committing, so no locks or deadlocks will occur;
  • It can respond to transactions quickly, but as the concurrency increases, a large number of rollbacks will occur;
  • High efficiency, but the locking force must be controlled.

【shortcoming】

  • If you simply do this, you may still encounter unexpected results. For example, two transactions both read a row from the database, and then write it back to the database after modification. This will cause problems.
  • As the concurrency increases, a large number of rollbacks will occur.

PCC Advantages and Disadvantages

【advantage】

The conservative strategy of "lock first and then access" ensures the security of data processing;

【shortcoming】

  • Relying on database locks, which is inefficient;
  • The locking mechanism will cause additional overhead to the database and increase the chance of deadlock;
  • This reduces parallelism. If a transaction locks a row of data, other transactions must wait for the transaction to be completed before they can process that row of data.

The above is the details of pessimistic locking and optimistic locking in MySQL. For more information about MySQL pessimistic locking and optimistic locking, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Examples of optimistic locking and pessimistic locking in MySQL
  • Examples of using MySQL pessimistic locking and optimistic locking
  • Understanding and application analysis of mysql pessimistic locking and optimistic locking
  • Comprehensive analysis of optimistic locking, pessimistic locking and MVCC in MySQL
  • MySQL pessimistic locking and optimistic locking implementation

<<:  How to Check Memory Usage in Linux

>>:  Vue's various implementation methods for modifying parent component props through child components

Recommend

Pricing table implemented with CSS3

Result: Implementation Code html <div id="...

vue2.x configuration from vue.config.js to project optimization

Table of contents Preface vue.config.js configura...

Detailed explanation of the problem of configuring servlet url-pattern in tomcat

When configuring web.xml for tomcat, servlet is a...

Specific operations of MYSQL scheduled clearing of backup data

1|0 Background Due to project requirements, each ...

Detailed explanation of Vue development Sort component code

Table of contents <template> <ul class=&...

Native JS realizes the special effect of spreading love by mouse sliding

This article shares with you a js special effect ...

Vue implements drag progress bar

This article example shares the specific code of ...

A simple tutorial on how to use the mysql log system

Table of contents Preface 1. Error log 2. Binary ...

Descending Index in MySQL 8.0

Preface I believe everyone knows that indexes are...

Solution for multiple Docker containers not having the same port number

Background In Docker, four containers are created...

MySQL 5.7.24 installation and configuration method graphic tutorial

MySQL is the most popular relational database man...

React configuration px conversion rem method

Install related dependencies npm i lib-flexible -...