当前位置:网站首页>Please, don't use pessimistic locks in high concurrency scenarios!
Please, don't use pessimistic locks in high concurrency scenarios!
2022-06-21 13:29:00 【Hollis Chuang】
△Hollis, One right Coding People with unique pursuit △

This is a Hollis Of the 394 Original sharing
author l Hollis
source l Hollis(ID:hollischuang)

We know , Optimistic lock and pessimistic lock are the main technical means of concurrency control , Usually used in database management .
however , Optimism lock 、 Pessimistic locks are not like row level locks 、 Shared lock and other concepts are also real locks . In fact, they are just concepts defined by people , It can be thought of as an idea . In fact, it is not only the concept of optimistic lock and pessimistic lock in relational database system , image memcache、hibernate、tair There are similar concepts .
For different business scenarios , Different concurrency control methods should be chosen . therefore , Don't take optimistic concurrency control and pessimistic concurrency control in a narrow sense as DBMS The concept of , Don't put them and the lock mechanism provided in the data ( Row lock 、 Table locks 、 Exclusive lock 、 Shared lock ) Confuse STH with STH else . Actually , stay DBMS in , Pessimistic lock is realized by using the lock mechanism provided by the database itself .
There are many introductions about optimistic lock and pessimistic lock on the Internet , I also have articles before (《 In depth understanding of optimistic lock and pessimistic lock 》) Specially introduced , Here, for the convenience of understanding , Just make a simple summary .
Pessimistic lock and optimistic lock
Pessimistic locking , As its name suggests , It refers to the pessimistic attitude towards the data being modified by the outside world , therefore , In the whole data processing process , You need to lock the data first , Operate after obtaining the lock .
stay MySQL in , You can use exclusive locks to implement pessimistic locks , It mainly uses select ... for update grammar .
Use pessimistic locks , Need to be closed mysql Auto-commit properties for the database :set autocommit=0;
Then in the transaction , Lock the data with the following statement :
select status from t_goods where id=1 for updateabove , In the face of id = 1 Before the modification of the records , Through the first for update The way to lock , And then make changes . This is a typical pessimistic lock strategy .
If the above inventory modification code is concurrent , At the same time, only one thread can start a transaction and get id=1 Lock of , Other transactions must wait until this transaction is committed . This ensures that the current data is not modified by other transactions .
Relative to pessimistic locks , The optimistic locking assumption assumes that data in general will not cause collisions , So when the data is submitted for update , The data conflict will be formally detected or not , If there is a conflict , Returns the user's error message , Let the user decide how to do it .
The implementation of optimistic locking does not use the locking mechanism provided by the database . The general way to implement optimistic locking is to record the data version , As below SQL:
update t_goods
set status=2,version=version+1
where id=#{id} and version=#{version}Difference between the two
above , We learned about the idea of optimistic lock and pessimistic lock, and realized it , Discuss their differences .
First , The locking time is different , Pessimistic locking is locking at the beginning of a transaction , After you get the lock, you can perform business operations . Optimistic locks, on the other hand, do not control concurrency until they are updated , So it is the first business operation .
secondly , Pessimistic lock is mainly realized by means of exclusive lock of database , The exclusive lock is essentially a blocking lock . If the concurrency is large and there are many conflicts , This will cause many threads to be blocked by locks , The result of the request RT Elongated , And it will occupy a lot of database links .
by comparison , Optimistic locks do not cause congestion , But the problem it brings is that if the concurrency conflict is high , Then there will be many failures , The business code is required to handle such failures .
The third point , That's it Optimistic lock is called lock , But he didn't add an extra lock , It's through CAS To achieve , So he is more efficient , Pessimistic locks need to be locked by using the database locking mechanism , This will bring some additional cost .
And finally , It's also more important , That's it Pessimistic lock because of the action of locking , So it will lead to deadlock .
Do not use pessimistic locks for high concurrency
I strongly recommend that you , Give priority to optimistic locks , Especially, the concurrency is high , And there are many conflicts .
Because we mentioned earlier , Pessimistic locks have an additional cost 、 And it may cause deadlock . But these are not the most important .
most important of all , Pessimistic lock is essentially a blocking lock , In the case of high concurrency , There will be many threads blocked , These blocked threads will occupy the database links . Therefore, the concurrency of your system will be very low , In addition, the response time of these blocked threads will be very long , Extremely affecting the user experience , There will be a lot more slow SQL.
One extra sentence , stay MySQL 8.0 in , Has supported select ... for update nowait, You can turn a blocking lock into a non blocking lock . Some problems caused by pessimistic lock blocking can be solved to some extent , However, the additional cost of locking and the problem of deadlock still exist .
therefore , In high concurrency scenarios , It is recommended to use optimistic lock , In especial MySQL 5.x In the version of the , Because it's not supported nowait, Once the pessimistic lock is used , It will greatly reduce the concurrency of your system .

End
My new book 《 In depth understanding of Java The core technology 》 It's on the market , After listing, it has been ranked in Jingdong best seller list for several times , At present 6 In the discount , If you want to start, don't miss it ~ Long press the QR code to buy ~

Long press to scan code and enjoy 6 A discount
Previous recommendation It's a hot topic : a monthly salary 2~3W The Manon of , How to spend the day ?
It's still in use SimpleDateFormat Format the time ? Be careful of project collapse !
Start a new company , How to get familiar with code quickly ?
If you enjoyed this article ,
Please hold on to the QR code , Focus on Hollis.

Forward to circle of friends , It was my greatest support .
Order one Looking at
Like is a feeling
Looking is a kind of support
边栏推荐
- 【深入理解TcaplusDB技术】TcaplusDB业务数据备份
- 【深入理解TcaplusDB技术】Tmonitor后台一键安装
- 百度交易中台之钱包系统架构浅析
- 【深入理解TcaplusDB技术】Tmonitor系统升级
- 修修补补一时爽,果断重构有担当——聊聊CRM分布式缓存优化
- 7. pointer
- Summary of the latest remote deployment O & M tools
- Kubernets Rapid Practical fighting and Core Principle Analysis
- 还在用generator生成xxx管理系统的CRUD代码?来看看我是怎么写的
- Graveyard
猜你喜欢

618 Nuggets digital collection? Burberry and other luxury brands fight against metauniverse

高效远程办公手册| 社区征文

【深入理解TcaplusDB技术】TcaplusDB导入数据

Apache ShardingSphere 5.1.2 发布|全新驱动 API + 云原生部署,打造高性能数据网关

Repair for a while, decisively reconstruct and take responsibility -- talk about CRM distributed cache optimization

Kubernetes' fast practice and core principle analysis

2022年中国手机银行年度专题分析

Flink CDC MongoDB Connector 的实现原理和使用实践

TOOD: Task-aligned One-stage Object Detection

Work content of service governance
随机推荐
Repair for a while, decisively reconstruct and take responsibility -- talk about CRM distributed cache optimization
Analysis on the wallet system architecture of Baidu trading platform
Test the interface between app and wechat applet
Hands on data analysis unit 2 section 4 data visualization
如何使用搜索引擎?
启牛商学院app下载证券开户,是安全的吗?有风险嘛?
May the mountains and rivers be safe
还在用generator生成xxx管理系统的CRUD代码?来看看我是怎么写的
对app和微信小程序进行接口测试
《預訓練周刊》第50期:無解碼變換器、神經提示搜索、梯度空間降維
2. data type
如何使用搜索引擎?
Consultation: what kind of securities company is micro securities? Is it safe to open an account?
Not only zero:bmtrain technology principle analysis
Unbounded territory won the title of innovative brand of digital culture industry in 2022
seaborn数据总体分布的可视化策略
Sharing new experiences in home office | community essay solicitation
Numpy | insert variable length character array test OK
Turn to the countdown for coupon issuance! First look at the rules of interstellar pocket donation
Implementation principle and application practice of Flink CDC mongodb connector


