当前位置:网站首页>Source code analysis of cyclicbarrier in AQS
Source code analysis of cyclicbarrier in AQS
2022-06-09 05:15:00 【smartjiang-java】
1:CyclicBarrier Basic knowledge
1: It literally means recyclable (Cyclic) The barrier (Barrier). When a group of threads all reach the barrier , The barrier will open , The thread blocked by the barrier will continue to run . The thread that arrives first is blocked .
2: Use scenarios : It can be used for multithreading data , Scenario of the last merged results .
3:CountDownLatch Can only be used once , and CyclicBarrier The counter of can be used reset() Method reset .
4: It is generally used with a fixed number of thread pools , The number of threads is best defined the same
2: Construction method
Default constructor : Total number of incoming intercepted threads
public CyclicBarrier(int parties) {
// Call overloaded method , That is, another construction method
this(parties, null);
}
Enter overloaded method : Another construction method
public CyclicBarrier(int parties, Runnable barrierAction) {
// The number of threads intercepted cannot <=0, Otherwise, an exception will be thrown
if (parties <= 0) throw new IllegalArgumentException();
// Pass in a task , When the thread reaches the barrier , Give priority to this task
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}
3: Blocking method await
The thread that needs to wait needs to call await() Method
public int await() throws InterruptedException, BrokenBarrierException {
try {
// Get into dowait(false, 0L) Method
return dowait(false, 0L);
} catch (TimeoutException toe) {
throw new Error(toe); // cannot happen
}
}
Get into dowait(false, 0L) Method
private int dowait(boolean timed, long nanos)
throws InterruptedException, BrokenBarrierException,
TimeoutException {
// It can be seen that there is a ReentrantLock lock
final ReentrantLock lock = this.lock;
// Before executing the logic , You need to lock it first
lock.lock();
try {
final Generation g = generation;
if (g.broken)
throw new BrokenBarrierException();
if (Thread.interrupted()) {
breakBarrier();
throw new InterruptedException();
}
// Number of barriers reduce 1 , Judge reduce 1 Whether the latter is equal to 0
int index = --count;
if (index == 0) {
boolean ranAction = false;
try {
// If the priority task passed in by the constructor is not null, priority
final Runnable command = barrierCommand;
if (command != null)
command.run();
ranAction = true;
// Get into nextGeneration() Method
nextGeneration();
return 0;
} finally {
if (!ranAction)
breakBarrier();
}
}
for (;;) {
try {
if (!timed)
trip.await();
else if (nanos > 0L)
nanos = trip.awaitNanos(nanos);
} catch (InterruptedException ie) {
if (g == generation && ! g.broken) {
breakBarrier();
throw ie;
} else {
Thread.currentThread().interrupt();
}
}
if (g.broken)
throw new BrokenBarrierException();
if (g != generation)
return index;
if (timed && nanos <= 0L) {
breakBarrier();
throw new TimeoutException();
}
}
} finally {
lock.unlock();
}
}
Get into nextGeneration() Method
private void nextGeneration() {
// Get into Condition.signalAll() Method
trip.signalAll();
count = parties;
generation = new Generation();
}
Get into Condition.signalAll() Method
public final void signalAll() {
// Judge to have ReentrantLock Whether the thread of the lock is the current thread , If not, throw an exception
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
// Conditinon The first node in , If it's not empty , Get into doSignalAll(first) Method
Node first = firstWaiter;
if (first != null)
doSignalAll(first);
}
Get into doSignalAll(first) Method
private void doSignalAll(Node first) {
// take Conition Node delete moved to AQS Waiting in the queue , It's just that the order of all nodes is pushed back by one bit , The head node is a sub element node
lastWaiter = firstWaiter = null;
do {
Node next = first.nextWaiter;
first.nextWaiter = null;
transferForSignal(first);
first = next;
} while (first != null);
}
go back to nextGeneration() Method
private void nextGeneration() {
// Condition.signalAll() : take Condition Node deletion moved to AQS Waiting in line
trip.signalAll();
count = parties;
// Create a new instance , Each new use of the barrier creates an instance
generation = new Generation();
}
go back to dowait(false, 0L) Method
private int dowait(boolean timed, long nanos)
throws InterruptedException, BrokenBarrierException,
TimeoutException {
// It can be seen that there is a ReentrantLock lock
final ReentrantLock lock = this.lock;
// Before executing the logic , You need to lock it first
lock.lock();
try {
final Generation g = generation;
if (g.broken)
throw new BrokenBarrierException();
if (Thread.interrupted()) {
breakBarrier();
throw new InterruptedException();
}
// Number of barriers reduce 1 , Judge reduce 1 Whether the latter is equal to 0
int index = --count;
if (index == 0) {
boolean ranAction = false;
try {
// If the priority task passed in by the constructor is not null, priority
final Runnable command = barrierCommand;
if (command != null)
command.run();
ranAction = true;
// Get into nextGeneration() Method
nextGeneration();
return 0;
} finally {
// ranAction be equal to true, Not meeting the conditions
if (!ranAction)
breakBarrier();
}
}
// Number of barriers reduce 1 Greater than 0, If entering for loop
for (;;) {
try {
// If there is no transmission waiting time , So enter Condition.await() Method ; Otherwise, enter the timeout Condition.awaitNanos() Method
// Generate a new node , Add to Conditon The end of a two-way linked list , Release the synchronization lock held on the node , And blocked
if (!timed)
trip.await();
else if (nanos > 0L)
nanos = trip.awaitNanos(nanos);
} catch (InterruptedException ie) {
if (g == generation && ! g.broken) {
breakBarrier();
throw ie;
} else {
Thread.currentThread().interrupt();
}
}
if (g.broken)
throw new BrokenBarrierException();
if (g != generation)
return index;
if (timed && nanos <= 0L) {
breakBarrier();
throw new TimeoutException();
}
}
} finally {
// Last ReentrantLock To unlock
lock.unlock();
}
}
边栏推荐
- Codeigniter3 learning notes 5 (form verification)
- EF core uses scaffold dbcontext to generate model from database
- pytest_allure优先级、fixture-scope参数介绍
- 关于全局异常捕获的思考-真正的全局异常捕获
- 2022 "Cyberspace Security" event module B of Jiangxi secondary vocational group - SQL injection test
- AQS 之 ReentrantReadWriteLock 源码分析
- [006] [esp32 Development notes] burn firmware steps Using Flash Download Tool
- Sword finger: duplicate number in array (JS)
- 内网渗透 - 哈希传递攻击
- Li Kou today's question -1037 Effective boomerang
猜你喜欢

Openstack Learning Series 12: installing CEPH and docking openstack

三方账号授权登录系统设计思路
![[006] [esp32 Development Notes] steps for burning firmware using flash download tool](/img/a0/5d5e6c076d267c0ffe4c1e8f10e408.png)
[006] [esp32 Development Notes] steps for burning firmware using flash download tool

Load research of Marathon LB

Caching mechanism in transformer

聊聊保证线程安全的10个小技巧

Summary of Android Engineer interview experience with 5 years' work experience, summary of real interview questions of Ali + Tencent + byte jump

好榛子出辽阳!

Soft keyboard appears search

ps如何给图像加边框
随机推荐
Talk about 10 tips to ensure thread safety
. Net core 3.0 grpc custom service
Typescript learning [7] advanced types: Union type and cross type
MQ message loss, message consistency, repeated consumption solution
Recurrence and solution of long jump in data warehouse
由id获取name调用示例(腾讯IM)
AQS 之 CyclicBarrier 源码分析
2022 tea artist (intermediate) examination question simulation examination question bank and simulation examination
2021 national vocational skills competition Liaoning "Cyberspace Security Competition" and its analysis (ultra detailed)
1- enter the database
TypeScript 学习【9】泛型
2022 welder (elementary) special operation certificate examination question bank and simulation examination
2022 "Cyberspace Security" event module B of Jiangxi secondary vocational group - SQL injection test
The website is frequently suspended, leading to a decline in ranking
好榛子出辽阳!
1030. 距离顺序排列矩阵单元格●
Finding JS in the two-dimensional array of sword fingers (clear version)
TCP explanation (Wireshark packet capturing analysis TCP three handshakes and TCP four waves)
Penetration test path dictionary, blasting dictionary
Previous improvements of CSDN products (up to issue 29)