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

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

4.如何选择
- 乐观锁适用于读多写少的场景,可以省去频繁加锁、释放锁的开销,提高吞吐量
- 在写比较多的场景下,乐观锁会因为版本不一致,不断重试更新,产生大量自旋,消耗 CPU,影响性能。这种情况下,适合悲观锁
边栏推荐
- ctf MISC 学习总结「建议收藏」
- Solution to connection rejected error in idea download sources
- 【215】gin框架連接mysql數據庫
- CSDN custom T-shirts are waiting for you to get, and the benefits of new programmer are coming!
- Une erreur s'est produite lors de la configuration du login du moteur Gom: aucun correctif requis n'a été trouvé!
- MySQL8.0.23四次重装都失败在 'Writing configuration file'
- 卡方分布、方差分析
- Trust counts the number of occurrences of words in the file
- Keras II classification problem
- [215] gin framework connects to MySQL database
猜你喜欢

Sentinel installation diagram

MySQL 66 questions, 20000 words + 50 pictures, including (answer analysis)

薪资高压线

Common operations of idea debug

MySQL massive write problem optimization scheme MySQL parameter tuning

Explication détaillée du principe de co - intégration en go

变分法 (Calculus of Variations)

leetcode:剑指 Offer II 115. 重建序列【图论思维 + 入度考虑 + 拓扑排序】

Keras之二分类问题

Keras II classification problem
随机推荐
Eric6 installation problem
Use of keyup.native in El input
Seal player IP and machine code and unlock the blocked tutorial
微服务雪崩问题及解决方案
go中高并发下的锁是如何工作的(结合源码)
Detailed explanation of CO process principle in go
Reinforcement learning -- Markov decision process MP MRP MDP
吉时利静电计在新能源电池测试方案的应用
IDEA Download Sources报错 Connection refused的解决方法
Calculus of variations
[215] gin framework connects to MySQL database
Type-C to OTG (USB2.0 data transmission) + PD charging protocol chip ledrui ldr6028/ldr6023ss
VIM notes
C language -- implementation of address book and screentogif
leetcode:剑指 Offer II 115. 重建序列【图论思维 + 入度考虑 + 拓扑排序】
rust猜数字游戏
jps详解
多线程编程
Common work operations
MYSQL基础及性能优化