当前位置:网站首页>Interviewer: Have you ever used a lock at work?Talk about the advantages, disadvantages and usage scenarios of optimistic locking and pessimistic locking
Interviewer: Have you ever used a lock at work?Talk about the advantages, disadvantages and usage scenarios of optimistic locking and pessimistic locking
2022-08-08 08:34:00 【Hao elder brother to learn programming】
What problems can optimistic and pessimistic locking solve?
In a concurrent scenario, update a record in an orderly manner.
What is optimistic locking and what is pessimistic locking?
Optimistic locking: Optimistic locking is very optimistic when operating data, thinking that others will not modify the data at the same time.
Therefore, the optimistic lock will not be locked, but when performing the update, it is judged whether others have modified the data during this period: if others have modified the data, the operation will be abandoned, otherwise the operation will be performed.
Pessimistic lock: Pessimistic lock is pessimistic when operating data, thinking that others will modify the data at the same time.
Therefore, the data is directly locked when operating the data, and the lock will not be released until the operation is completed; other people cannot modify the data during the locking period.
How should the two locks be implemented?
There are two main ways to implement optimistic locking: CAS mechanism and version number mechanism
CAS: (Compare And Swap)
CAS operation consists of 3 operands:
1) The memory location that needs to be read and written (V)2) Expected value for comparison (A)3) New value to be written (B)The operation logic is as follows:
If the value of memory location V is equal to the expected value of A, update the location to the new value B, otherwise do nothing.
Many CAS operations are spin: if the operation is unsuccessful, it will be retried until the operation succeeds.
This leads to a new question. Since CAS includes two operations, Compare and Swap, how does it ensure atomicity?
The answer is: CAS is an atomic operation supported by the CPU, and its atomicity is guaranteed at the hardware level.
Note: The auto-increment operation
(i++)in Java cannot get 100% accurate results in concurrent scenarios because it is not an atomic operation.In concurrent scenarios,
AtomicIntegershould be used for auto-increment operation, which is also internally implemented by CAS optimistic locking.
Version
The basic idea of the version number mechanism is to add a field version to the data, indicating the version number of the data. Whenever the data is modified, the version number is incremented by 1.
- When a thread queries data, find out the version number of the data together;
- When the thread updates the data, it is judged whether the current version number is consistent with the version number read before, and the operation is performed only if they are consistent.
It should be noted that the version number is used here as a mark for judging data changes. In fact, other fields that can mark the data version, such as timestamp, can be selected according to the actual situation.
Two implementations of pessimistic locks: synchronized and select...for update
The code implements pessimistic locks: synchronized
Synchronized locks the code block to achieveGuaranteed thread safety: at a time, only one thread can execute the code in the code block.
synchronized is a heavyweight operation, not only because locking needs to consume additional resources, but also because the switching of thread state will involve the conversion of operating system kernel state and user state;
However, with the JVM's series of optimizations on locks (such as spin locks, lightweight locks, lock coarsening, etc.), the performance of synchronized has been getting better and better.
sql implements pessimistic lock select...for update
The query statement will add an exclusive lock to the row record, and the exclusive lock will not be released until the transaction is committed or rolled back;
During this period, if other transactions can only perform query operations on this row of records, if they update the row's record information or execute select for update, they will be blocked.
ps: When using select for update, you must keep up with the condition of where id = ?. The id field must be the primary key or unique index. Otherwise, the entire table will be locked, and the consequences will be serious!
Analyze the advantages and disadvantages of the two locks?
Optimistic lock
Advantages:
- Lightweight lock, avoiding the overhead of thread switching.
Disadvantages:
- There will be ABA problems
Assuming there are two threads - thread 1 and thread 2, the two threads perform the following operations in order
(1) Thread 1 reads the data in memory as A;
(2) Thread 2 modifies the data to B;
(3) Thread 2 modifies the data to A;
(4) Thread 1 performs CAS operation on data
In step (4), since the data in memory is still A, the CAS operation is successful, but the data has actually been modified by thread 2.This is the ABA problem.
Only a single variable can be locked
Spin operation incurs overhead
pessimistic lock
Advantages:
- Because the lock is a block of code, multiple variables can be locked.
Disadvantages:
- Heavyweight locks, locking and releasing locks will have overhead, and context switching and thread scheduling at the operating system level will also cause a lot of overhead.
- A thread holding a lock causes all other threads that need the lock to hang.
How to choose optimistic lock and pessimistic lock in different scenarios?
Under high concurrency and high competition, in order to avoid retry overhead, pessimistic locks are directly selected.
For example, when booking a train ticket, it is displayed on the screen that there is a ticket. When the ticket is actually issued, it needs to be re-confirmed that this data has not been modified by other clients.So, in this confirmation process, you can use for update.
The concurrency situation is not intense, occasionally solve the concurrency problem, and choose optimistic locks with low performance consumption.
边栏推荐
猜你喜欢

BLOB, TEXT, GEOMETRY or JSON column ‘xxxx‘ can‘t have a default value

regular expression

Today share how to submit a bug

【vulhub】PostGresql高权限命令执行漏洞复现(CVE-2019-9193)

双馈风电机组备用容量控制策略研究

DVWA full level detailed customs clearance tutorial

idea big data tools submit flink tasks

在数学里,minimum 和 minimal 有啥区别吗?

教你实现多线程案例定时器

【项目问题】Ionic开发移动端app,手把手教你如何打包生成apk
随机推荐
百度飞浆EISeg高效交互式标注分割软件的使用教程
关于 QtCreator使用msvc2017x64编译器编译项目报错”编译器的堆空间不足“错误 的解决方法
STL 底层实现原理
golang-channel-一个基础channel并行操作的简单函数
flink sql创建表成功,查询却报错block data,大家有没有碰到这现象
【图像分类】2021-CoAtNet NeurlPS
matlab simulink串级变比值模糊PID烟气脱硫浆液pH值控制
Do you really know IP addresses?
Raspberry pie 】 【 without WIFI even under the condition of the computer screen
Spark2 struct SQL processing
The basic method of use in the volatile in the C language
My MySQL installation that is how to solve
大文件上传时如何做到 秒传?
生成密码字典的方法
What exactly happens after entering the URL in the browser?
微软 .NET Core 3.1 年底将结束支持,请升级到.NET 6
入职半个月的一些思考
【收藏】3. 壁纸收藏
regular expression
文件包含漏洞-知识点