当前位置:网站首页>[redisson] source code analysis of multilock
[redisson] source code analysis of multilock
2022-06-22 22:55:00 【Roll a few you WOW】
Keep creating , Accelerate growth ! This is my participation 「 Nuggets day new plan · 6 Yuegengwen challenge 」 Of the 25 God , Click to see the event details
Redisson Distributed lock support MultiLock Mechanism : You can combine multiple locks into one big lock , Apply for and release a large lock in a unified way .
Lock multiple resources at once , Then deal with the logic , Finally, release the lock corresponding to all resources at one time .
In the real world : Lock stock 、 Lock order 、 Lock the integral .
This may operate in the database , Use row lock .
Take a chestnut :
@Test
public void test() {
RLock lock1 = redisson.getLock("lock1");
RLock lock2 = redisson.getLock("lock2");
RLock lock3 = redisson.getLock("lock3");
RLock multiLock = redisson.getMultiLock(lock1, lock2, lock3);
multiLock.lock();
multiLock.unlock();
}
First look Get the lock :RLock multiLock = redisson.getMultiLock(lock1, lock2, lock3);
actually : Just take an array to store these locks .
// RedissonMultiLock.java
// Put it in a list
final List<RLock> locks = new ArrayList<>();
public RedissonMultiLock(RLock... locks) {
if (locks.length == 0) {
throw new IllegalArgumentException("Lock objects are not defined");
}
this.locks.addAll(Arrays.asList(locks));
}
(1) Lock
// RedissonMultiLock.java
@Override
public void lock() {
try {
lockInterruptibly();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
@Override
public void lockInterruptibly() throws InterruptedException {
lockInterruptibly(-1, null);
}
@Override
public void lockInterruptibly(long leaseTime, TimeUnit unit) throws InterruptedException {
// 1. Calculate the waiting time
// Waiting time = Number of locks * 1500, 3 Lock rule 4500
long baseWaitTime = locks.size() * 1500;
long waitTime = -1;
if (leaseTime == -1) {
waitTime = baseWaitTime;
} else { // Custom waiting time
leaseTime = unit.toMillis(leaseTime);
waitTime = leaseTime;
if (waitTime <= 2000) {
waitTime = 2000;
} else if (waitTime <= baseWaitTime) {
waitTime = ThreadLocalRandom.current().nextLong(waitTime/2, waitTime);
} else {
waitTime = ThreadLocalRandom.current().nextLong(baseWaitTime, waitTime);
}
}
// 2. Wait for all locks to succeed
while (true) {
if (tryLock(waitTime, leaseTime, TimeUnit.MILLISECONDS)) {
return;
}
}
}
This process , It is mainly divided into two parts :
- Calculate the waiting time : Related to the number of locks ; 3 A lock , Waiting time = 3 * 1500 = 4500
- Try to apply all locks : Infinite loop , Until all locks are added successfully
Get into tryLock(), Look at its source code :
@Override
public boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
// 1. Traversal attempts to lock each lock
// As long as one lock fails to lock , Unlock the previous , Then lock it again
// A bunch of logic , Don't let it be
{...}
// 2. A lock has a time limit , Asynchronous expiration check
{...}
return true;
}
How long must it take to acquire all the locks , If it times out, it will try to acquire the lock again .
The use of each lock tryLock() Method , Specifies that when acquiring each individual lock , There will be a timeout exit time .
(2) Release the lock
@Override
public void unlock() {
List<RFuture<Void>> futures = new ArrayList<>(locks.size());
// Asynchronous release lock
// The release of the lock , For specific locks , It's not going to unfold here .
for (RLock lock : locks) {
futures.add(lock.unlockAsync());
}
// Wait for all locks to release
for (RFuture<Void> future : futures) {
future.syncUninterruptibly();
}
}
边栏推荐
- R language data preprocessing, converting type variables into factor variables, converting data sets into H2O format, and dividing data sets (training set, test set, verification set)
- 2021-07-27
- Huawei cloud recruits partners in the field of industrial intelligence to provide strong support + commercial realization
- LinkedList source code analysis
- [recommended by Zhihu knowledge master] castle in UAV - focusing on the application of UAV in different technical fields
- The xinjietu x70s has been listed for 87900 times and has leapfrogged the class in space safety. It is worthy of being a 7-seat SUV of the National University of China
- Introduction and example application of PostgreSQL string separator function (regexp\u split\u to\u table)
- 2020-12-20
- Grafana report display of sentinel based high availability current limiting system
- One case of SQL performance degradation caused by modifying implicit parameters
猜你喜欢

The relationship between derivative and differential of function

2021-04-14

Las point cloud create mesh

Some shaders in AB package do not trigger the callback of ipreprocessshaders
![组合总数[标准回溯 + 回溯技巧--降低栈深度]](/img/88/3a07589bf8edab618139b1bf1680e8.png)
组合总数[标准回溯 + 回溯技巧--降低栈深度]

General trend wisdom to create inclined model and cut monomer
![[geometric vision] 4.2 piecewise linear transformation](/img/1e/a810f4d7e9a6a34647b5cb56fdde67.png)
[geometric vision] 4.2 piecewise linear transformation

Reinforcement learning weekly (issue 50): saferl kit, gmi-drl, rp-sdrl & offline meta reinforcement learning

Why do you perform performance tests before the software goes online? How to find a software performance testing organization

安装typescript环境并开启VSCode自动监视编译ts文件为js文件
随机推荐
Makefile:1860: recipe for target ‘cmake_ check_ build_ system‘ failed make: *** [cmake_check_build_syst
2021-08-21
Mysql database DML operation exercise
2020-12-20
Eureka service registration and discovery
Which securities company is the safest and best choice for stock trading account opening
2021-08-26
Technology cloud report: East to West computing is not only about "computing", but also needs "new storage"
2020-12-20
How to continuously improve performance| DX R & D mode
From 11 hours to 25 seconds -- is there room for optimization?
《强化学习周刊》第50期:SafeRL-Kit、GMI-DRL、RP-SDRL & 离线元强化学习
[path planning] week 1: hodgepodge
Next permutation [give play to subjective initiative to discover laws]
Redis big key problem
Las point cloud create mesh
Help customers' digital transformation and build a new operation and maintenance system
Solution to cache inconsistency
Delphi SOAP WebService 服务器端多个 SoapDataModule 要注意的问题
AtCoder abc256全题解(区间合并模板、矩阵快速幂优化dp、线段树……)