当前位置:网站首页>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,
AtomicInteger
should 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.
边栏推荐
猜你喜欢
随机推荐
数学基础(二)逆矩阵、伪逆矩阵、最小二乘解、最小范数解
【树莓派】vim编辑器
数据库_JDBC
Matlab实现异构交通流
文献学习(part33)--Clustering by fast search and find of density peaks
C#实现在企业微信内发送消息给指定人员帮助类
[Raspberry Pi] vim editor
Implementation principle of priority queue
Want to use SQL to achieve two days after the data contrast, the new data sheet and a list of tags
多态案例2 制作饮品
Spark2 struct SQL processing
golang-channel-一个基础channel并行操作的简单函数
[ 深度学习 ] 课程学习(Curriculum Learning)
【Enumeration】Continuous factor
goroutine 调度
要写脚本,编程不好不要紧--浅谈CTF中脚本的编写方法
【树莓派】在没有显示屏的情况下通过WIFI连电脑
STL 底层实现原理
业内首个「因果推断全流程」挑战赛!WAIC 2022 · 黑客马拉松邀全球开发者精英来挑战
Excel中text函数5中常用方法