当前位置:网站首页>[redis realizes seckill business ③] specific implementation of optimistic lock for oversold problem
[redis realizes seckill business ③] specific implementation of optimistic lock for oversold problem
2022-06-25 00:45:00 【Bulst】
List of articles
Version number method
There are also two common ways to implement the version number mechanism :
Use data version (Version) Record mechanism implementation , This is the most common implementation of optimistic locking . What is a data version ? Add a version identity to the data , This is generally done by adding a number type to a database table “version” Field to implement . When the data is read , take version The values of the fields are read together , The data is updated every time , Regarding this version Add the values of a .
When we submit the update , Judge the records corresponding to the database table The current version information of is the same as that of the first time version Value comparison , If the current version number of the database table is fetched for the first time version The values are equal , Is updated , Otherwise, it is considered to be outdated data .
If the update operations are executed in sequence , The version of the data (version) In turn, increasing , There is no conflict . However, if there are different business operations to repair the same version of data Change , that , The first submitted operation will send the data version Updated to 2, When A stay B The data is found when the update is submitted later version It has been modified , that A The update operation will fail .Use time stamps (timestamp). This implementation is similar to the first one , Also in need of optimistic lock control table Add a field to , Name doesn't matter , Field types use timestamps (timestamp), And the above version similar , Also check the timestamp of the data in the current database when the update is submitted and compare it with the timestamp obtained before the update , If consistent OK, Otherwise it's a version conflict .

CAS Algorithm
CAS namely Compare And Swap( Comparison and exchange ), It's a well-known unlocked algorithm . No lock programming , That is, to achieve variable synchronization between multiple threads without using locks , In other words, the synchronization of variables can be realized without thread blocking , So it's also called nonblocking synchronization (Non-blocking Synchronization).
CAS An operation contains three operands —— Value of memory location (V)、 The original value of the expected (A) And the new value (B). perform CAS During operation , Compare the value of the memory location with the expected original value , If they match , The processor will automatically update the location value to the new value , otherwise , The processor does nothing .
Through optimistic lock + The way you spin , Solve the thread safety problem of data update , And the lock granularity is lower than that of mutex , Good concurrency performance .
Cycle to achieve :
public void addCount(String goodsId, Integer count) {
while(true) {
Goods goods = dao.selectByGoodsId(goodsId);
if (goods == null) {
throw new Execption(" The data doesn't exist ");
}
int count = goods.getCount() + count;
goods.setCount(count);
int count = dao.updateCount(goods);
if (count > 0) {
return;
}
}
}
Recursive implementation :
public void addCount(String goodsId, Integer count) {
Goods goods = dao.selectByGoodsId(goodsId);
if (goods == null) {
throw new Execption(" The data doesn't exist ");
}
int count = goods.getCount() + count;
goods.setCount(count);
int count = dao.updateCount(goods);
if (count == 0) {
addCount(goodsId, count)
}
}
CAS Disadvantages of the algorithm
【1】 The cycle time is long and the cost is high : The spin CAS If it doesn't work for a long time , Will give CPU It's very expensive to execute .
【2】 Only one atomic operation of shared variables can be guaranteed : Only one atomic operation of shared variables can be guaranteed . When operating on a shared variable , We can use cycles CAS The way to guarantee atomic operation , But when operating on multiple shared variables , loop CAS There is no guarantee of atomicity of operation , You can use the lock at this time , Or there's a clever way , It is to combine multiple shared variables into a shared variable to operate . For example, there are two shared variables i=2,j=a, Merge ij=2a, And then use CAS To operate ij. from Java1.5 Start JDK Provides AtomicReference Class to ensure atomicity between reference objects , You can put multiple variables in one object CAS operation .
【3】ABA problem : because CAS It is necessary to check whether there is any change in the lower value when operating the value , Update if nothing changes , But if a value turns out to be A, Turned into B, It's changed again. A, So use CAS Check that its value has not changed , But it actually changed .ABA The solution to the problem is to use version number . Append the version number to the variable , Add the version number to each variable update 1, that A-B-A Will become 1A-2B-3A.
The illustration

Code implementation
We can do this in the following way , If the quantity is equal to the quantity you find , Just buy
// If the quantity is equal to the quantity you find , Just buy
boolean updateBoolean = this.update().setSql("count = count - 1")
.eq("id", id).eq("count", fruits.getId()).update();
if (!updateBoolean) {
return ResponseEntity.status(400).body(" The fruit is sold out , Come again next time !");
}
But this will make it impossible for other users who should be able to buy , So the changes are as follows
// If the quantity is equal to the quantity you find , Just buy
// boolean updateBoolean = this.update().setSql("count = count - 1")
// .eq("id", id).eq("count", fruits.getId()).update();
// If the remaining quantity is greater than 0, You can buy
boolean updateBoolean = this.update().setSql("count = count - 1")
.eq("id", id).gt("count", 0).update();
if (!updateBoolean) {
return ResponseEntity.status(400).body(" The fruit is sold out , Come again next time !");
}
边栏推荐
- 【微服务|Sentinel】实时监控|RT|吞吐量|并发数|QPS
- Only positive integers can be entered in the text box
- [interview question] the difference between instancof and getclass()
- Creative SVG ring clock JS effect
- UE4 WebBrowser chart cannot display problems
- C program design topic 15-16 final exam exercise solutions (Part 1)
- Xcode预览(Preview)显示List视图内容的一个Bug及解决
- Use and click of multitypeadapter in recycleview
- Go crawler framework -colly actual combat (IV) -- Zhihu answer crawl (I)
- placeholder
猜你喜欢

Sliding window technology based on byte in transport layer

The basic principle and application of iterator and enhanced for

百公里加速仅5.92秒,威兰达高性能版以高能产品实力领跑

Interesting checkbox counters

Virtual machine - network configuration

ros(25):rqt_ image_ View reports an error unable to load plugin for transport 'compressed', error string

2019 summary and 2020 outlook
Alternative to log4j

Activity startup process

ros(24):error: invalid initialization of reference of type ‘xx’ from expression of type ‘xx’
随机推荐
大厂高频软件测试面试题和答案都帮你准备好啦,备战金九银十
More pictures | explain the Nacos parameters in detail!
【Redis实现秒杀业务②】超卖问题的解决方案
The picture of wechat official account can not be displayed normally
Intensive reading of thinking about markdown
Applet opening traffic master
Previous basic review
Microsoft won the title of "leader" in the magic quadrant of Gartner industrial Internet of things platform again!
傳輸層 以字節為單比特的滑動窗口技術
百公里加速仅5.92秒,威兰达高性能版以高能产品实力领跑
Infotnews | is the development of domestic NFT limited to digital collections?
Basic summary of MySQL database knowledge
Paper review: U2 net, u-net composed of u-net
2021-02-15
在企业级开发过程中我发现有位同事用select * from where 条件 for update
Fuxin Kunpeng joins in, and dragon lizard community welcomes a new partner in format document technical service
JS dynamically generates variable names and assigns values
D manual destruction may violate memory security
Difficult and miscellaneous problems: A Study on the phenomenon of text fuzziness caused by transform
Realization of MNIST handwritten numeral recognition