Table of Contents
1. Lock
2. Pessimistic lock
3. Optimistic lock
4. How to choose
Home Database Mysql Tutorial How to apply pessimistic locking and optimistic locking in Mysql

How to apply pessimistic locking and optimistic locking in Mysql

Jun 02, 2023 pm 09:27 PM
mysql

1. Lock

In life: Locks are everywhere around us. For example, when I go out to play, I need to lock the door. For example, when I need to put money in a safe, I must lock it to ensure Security of my property.

In the code: For example, if multiple threads need to operate and modify shared variables at the same time, you need to lock the variable (syncronized) to ensure that the variable value is correct.

Database table: When multiple users modify the same data in the table, we can lock the row data (row lock).

sql script

CREATE TABLE `sys_user` (
  `id` bigint(20) NOT NULL COMMENT '主键ID',
  `name` varchar(30) DEFAULT NULL COMMENT '姓名',
  `age` int(11) DEFAULT NULL COMMENT '年龄',
  `email` varchar(50) DEFAULT NULL COMMENT '邮箱',
  `deleted` tinyint(1) DEFAULT NULL COMMENT '是否删除',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `create_id` bigint(20) DEFAULT NULL COMMENT '创建人',
  `update_id` bigint(20) DEFAULT NULL COMMENT '操作人',
  `update_time` datetime DEFAULT NULL COMMENT '更新时间',
  `status` varchar(255) DEFAULT NULL COMMENT '状态',
  `dog` text DEFAULT NULL COMMENT '狗',
  `version` int(11) DEFAULT NULL COMMENT '版本号',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `sys_user`(`id`, `name`, `age`, `email`, `deleted`, `create_time`, `create_id`, `update_id`, `update_time`, `status`, `dog`, `version`) VALUES (1, 'gukong', 19, 'test1@baomidou.com', 0, NULL, NULL, NULL, NULL, NULL, NULL, 0);
Copy after login

2. Pessimistic lock

When we want to modify a piece of data in the database, in order to avoid being modified by others at the same time, it is best to The solution is to directly lock the data to prevent concurrency.

Pessimistic lock is called pessimistic lock because it adopts a pessimistic concurrency control method, assuming that the data will be modified by other threads, so a locking operation will be performed when the data is modified. We generally believe that the probability of data being modified concurrently is relatively high, so it needs to be locked before modification.

Row locks, table locks, read locks, write locks, and syncronized locks in the database are all pessimistic locks.

mysql turns on pessimistic locking, example sql statement

--开启事务
BEGIN
--对行加锁
SELECT * FROM `sys_user` where id = 1 for UPDATE
--修改加锁行的数据
update sys_user set name = 'gukong',age = 18 where id = 1;
--提交事务
commit;
Copy after login
--开启事务
BEGIN
--对行加锁
SELECT * FROM `sys_user` where id = 1 for UPDATE
--修改加锁行的数据
update sys_user set name = 'kulilin',age = 20 where id = 1;
--提交事务
commit;
update sys_user set name = 'kulilin',age = 20 where id = 1;
Copy after login

How to apply pessimistic locking and optimistic locking in Mysql

3. Optimistic lock

Optimistic locking is to maintain optimism about data conflicts Attitude, when operating data, the operated data will not be locked. Only when the data is submitted, a mechanism will be used to verify whether there is a conflict in the data.

Optimistic locking is usually implemented by adding a version (version) or timestamp (timestamp) to the table. Among them, version is the most commonly used.

Optimistic lock will bring a version number every time it performs a data modification operation. Once the version number is consistent with the data version number, it can perform the modification operation and perform 1 operation on the version number, otherwise it will execute fail.

Optimistic lock example:

-- version = 0
SELECT * FROM `sys_user` where id = 1 
update sys_user set name='小明',version = version+1 and age = 20 where id = 1 and version = 0;
-- version = 0 ,而此时version=1,更新失败
SELECT * FROM `sys_user` where id = 1 
update sys_user set name = '小红' version = version+1 and age = 25 where id = 1 and version = 0;
Copy after login

How to apply pessimistic locking and optimistic locking in Mysql

4. How to choose

Optimistic lock is suitable for scenarios with more reading and less writing, and can be omitted The overhead of frequently locking and releasing locks improves throughput

When frequent write operations are required, using optimistic locks may produce a large amount of spins, consume CPU, and affect performance. The reason is that the version is inconsistent and retries are continued. renew. In this case, pessimistic locking is suitable

The above is the detailed content of How to apply pessimistic locking and optimistic locking in Mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Centos install mysql Centos install mysql Apr 14, 2025 pm 08:09 PM

Installing MySQL on CentOS involves the following steps: Adding the appropriate MySQL yum source. Execute the yum install mysql-server command to install the MySQL server. Use the mysql_secure_installation command to make security settings, such as setting the root user password. Customize the MySQL configuration file as needed. Tune MySQL parameters and optimize databases for performance.

See all articles