当前位置:网站首页>悲观锁和乐观锁
悲观锁和乐观锁
2022-07-23 15:51:00 【llp1110】
悲观锁和乐观锁
1.锁
生活中:锁在我们身边无处不在,比如我出门玩去了需要把门锁上,比如我需要把钱放到保险柜里面,必须上锁以保证我财产的安全。
代码中:比如多个线程需要同时操作修改共享变量,这时需要给变量上把锁(syncronized),保证变量值是对的。
数据库表:当多个用户修改表中同一数据时,我们可以给该行数据上锁(行锁)。
2.悲观锁
当我们要对数据库中的一条数据进行修改的时候,为了避免同时被其他人修改,最好的办法就是直接对该数据进行加锁以防止并发的发生。
为什么叫做悲观锁呢?因为这是一种对数据的修改抱有悲观态度的并发控制方式。我们一般认为数据被并发修改的概率比较大,所以需要在修改之前先加锁。
数据库中的行锁,表锁,读锁,写锁,以及 syncronized 实现的锁均为悲观锁。

3.乐观锁
乐观锁是对于数据冲突保持一种乐观态度,操作数据时不会对操作的数据进行加锁,只有到数据提交的时候才通过一种机制来验证数据是否存在冲突。
乐观锁通常是通过在表中增加一个版本(version)或时间戳(timestamp)来实现,其中,版本最为常用。
乐观锁每次在执行数据的修改操作时,都会带上一个版本号,一旦版本号和数据的版本号一致就可以执行修改操作并对版本号执行 +1 操作,否则就执行失败。

4.如何选择
- 乐观锁适用于读多写少的场景,可以省去频繁加锁、释放锁的开销,提高吞吐量
- 在写比较多的场景下,乐观锁会因为版本不一致,不断重试更新,产生大量自旋,消耗 CPU,影响性能。这种情况下,适合悲观锁
边栏推荐
- There is an error prompt when configuring the GOM engine login: the necessary patch file is not found!
- Detailed explanation of curl command [easy to understand]
- 吉时利静电计在新能源电池测试方案的应用
- MySQL 66 questions, 20000 words + 50 pictures, including (answer analysis)
- ctf MISC 学习总结「建议收藏」
- MYSQL基础及性能优化
- Go medium high parallel communication mode: the underlying principle of channel pipeline
- Eric6 installation problem
- 网分测花岗岩介电常数测试方案
- 分析一个 .NET 写的 某 RFID标签系统 CPU暴涨
猜你喜欢

MySQL 8.0.23 failed to reinstall for four times in'writing configuration file'

Une erreur s'est produite lors de la configuration du login du moteur Gom: aucun correctif requis n'a été trouvé!

go中高并发下的通信方式:channel管道的底层原理

"Nowadays, more than 99.9% of the code is garbage!"

Seal player IP and machine code and unlock the blocked tutorial

ContextLoaderListener vs DispatcherServlet

变分法 (Calculus of Variations)

Salary high voltage line

TwinCAT 3 首次运行报错4115

数字安全巨头Entrust披露六月遭到勒索软件团伙攻击
随机推荐
吉时利静电计在新能源电池测试方案的应用
MYSQL基础及性能优化
JS: image URL to Base64 encoding
LeetCode_ Dynamic programming_ Medium_ 120. Triangle minimum path sum
Mutual certification of product compatibility between tapdata and Youxuan database
RS232 DB9 serial port device
gom及gee架设黑屏的原因以及个别装备地图不显示怎么办?
Mpu9250 sensor
常用的curl命令及参数详解
MySQL六十六问,两万字+五十图详解含(答案解析)
QT multithread instance and the fifth parameter of connect [easy to understand]
Trust sums two numbers
vb连接Access数据库自定义
Paging class
Analyze the CPU surge of an RFID tag system written by.Net
ctf MISC 学习总结「建议收藏」
卡方分布、方差分析
Lin Zhiying is still in the intensive care unit and will undergo a second round of surgery: the police said he did not wear a seat belt
配置Gom引擎登錄器出現錯誤提示:沒有發現必備補丁文件!
Createfilemapping function "suggestions collection"