当前位置:网站首页>【高并发】关于乐观锁和悲观锁,蚂蚁金服面试官问了我这几个问题!!
【高并发】关于乐观锁和悲观锁,蚂蚁金服面试官问了我这几个问题!!
2022-06-10 10:13:00 【InfoQ】
何谓悲观锁与乐观锁
悲观锁
乐观锁
两种锁的使用场景
乐观锁的实现方式
版本号机制
- 操作员 A 此时将其读出(version=1 ),并从其帐户余额中扣除100-$50 )。
- 在操作员 A 操作的过程中,操作员 B 也读入此用户信息(version=1 ),并从其帐户余额中扣除100-$20 )。
- 操作员 A 完成了修改工作,将数据版本号加一(version=2 ),连同帐户扣除后余额(balance=$50 ),提交至数据库更新,此时由于提交数据版本大于数据库记录当前版本,数据被更新,数据库记录version 更新为 2 。
- 操作员 B 完成了操作,也将版本号加一(version=2 )试图向数据库提交数据(balance=$80 ),但此时比对数据库记录版本时发现,操作员 B 提交的数据版本号为 2 ,数据库记录当前版本也为 2 ,不满足 “ 提交版本必须大于记录当前版本才能执行更新 “ 的乐观锁策略,因此,操作员 B 的提交被驳回。
CAS 算法
- 需要读写的内存值 V
- 进行比较的值 A
- 拟写入的新值 B当且仅当 V 的值等于 A 时, CAS 通过原子方式用新值 B 来更新 V 的值,否则不会执行任何操作(比较和替换是一个原子操作)。一般情况下是一个自旋操作,即不断的重试。
乐观锁的缺点
ABA 问题
循环时间长开销大
只能保证一个共享变量的原子操作
CAS 与 synchronized 的使用场景
- 对于资源竞争较少(线程冲突较轻)的情况,使用 synchronized 同步锁进行线程阻塞和唤醒切换以及用户态内核态间的切换操作额外浪费消耗cpu 资源;而 CAS 基于硬件实现,不需要进入内核,不需要切换线程,操作自旋几率较少,因此可以获得更高的性能。
- 对于资源竞争严重(线程冲突严重)的情况, CAS 自旋的概率会比较大,从而浪费更多的 CPU 资源,效率低于 synchronized
边栏推荐
猜你喜欢

Notes to docker advanced (6) master-slave replication of MySQL in docker

Fastadmin uses phpexcel to export tabular data to excel

2023 Wangdao C language training camp (binary search tree - sequential search - half search)

stm32 printf乱码

一行代码制作数据分析交叉表,太便捷了

Leetcode 1991. 找到数组的中间位置(暴力枚举)

HPCA名人堂成员蒋晓维博士,任职大禹智芯首席科学家
![[edge detection] eight direction Sobel image edge detection based on MATLAB [including Matlab source code 1865]](/img/c8/039e7fc983905ae74e2d945dc6fbea.jpg)
[edge detection] eight direction Sobel image edge detection based on MATLAB [including Matlab source code 1865]

Chengdu test equipment customization_ A preliminary introduction to the data types of C language of single chip microcomputer

Xcode8.3.2 自动打包脚本
随机推荐
7、 Policy mode
「诗经」主题文化数字藏品中奖名单公布
MATLAB 学习笔记(3)MATLAB 矩阵的进阶操作
[image feature extraction] image feature extraction based on MATLAB pulse coupled neural network (PCNN) [including Matlab source code 1868]
Qchart note 1: simple linear diagram lineseries
PHP微信H5支付Demo
Uniapp message push (push by PHP server)
山东大学软件学院项目实训-创新实训-网络安全靶场实验平台(十六)
"Nonsense" database primary key design
六、观察者模式
MySQL - operation database
A unique resume generator, open source!
Axure pop-up settings
2022劳务员-岗位技能(劳务员)考试试题及答案
selenium分布式测试
Mixer: an indispensable component of video conference recording
mdb转换为db文件
Requirements and business model analysis - Requirements 16 - requirements validation
9、 Delegation mode
[edge detection] eight direction Sobel image edge detection based on MATLAB [including Matlab source code 1865]