Assuming all threads work in phase 0 of java phaser then one thread make arrive(); arrive(); arriveAndAwaitAdvance();
will this thread be waiting for phaser to end phase 2 or 0?
Asked
Active
Viewed 401 times
0

karol wołonciej
- 109
- 1
- 1
- 10
1 Answers
0
It depends on the number of threads (parties) on the Phaser. Simply phaser will wait a number of arrive() before advancing the phase.
Here is what will happen if you set the phaser with 2 parties:
- First, arrive() won't change the phase since we need 2.
- Second arrive() will change the phase from 0 to 1.
- arriveAndAwaitAdvance() operation won't change the phase from 1 to 2 since we need 2 arrive in order to advance.
So your thread will wait for phase 1 to end if the number of party in your Phaser is 2 (new Phaser(2);
).
Here is an example code that can help you to understand how phasers work:
ExecutorService executorService = Executors.newFixedThreadPool(2);
Phaser phaser = new Phaser(2);
executorService.execute(() -> {
System.out.println("First thread phase = " + phaser.getPhase());
phaser.arrive();
System.out.println("First thread After arrive1 = " + phaser.getPhase());
phaser.arrive();
System.out.println("First thread After arrive2 = " + phaser.getPhase());
phaser.arrive();
System.out.println("First thread After arrive3 = " + phaser.getPhase());
phaser.arrive();
System.out.println("First thread After arrive4 = " + phaser.getPhase());
phaser.arriveAndAwaitAdvance();
System.out.println("First thread After arriveAndAwaitAdvance = " + phaser.getPhase());
});
executorService.execute(() -> {
try {
Thread.sleep(2000);
System.out.println("Second thread current phase = " + phaser.getPhase());
phaser.arriveAndAwaitAdvance();
System.out.println("Second thread After arriveAndAwaitAdvance = " + phaser.getPhase());
} catch (InterruptedException e) {
e.printStackTrace();
}
});
executorService.shutdown();
The output of this code piece is:
First thread phase = 0
First thread After arrive1 = 0
First thread After arrive2 = 1
First thread After arrive3 = 1
First thread After arrive4 = 2
Second thread current phase = 2
Second thread After arriveAndAwaitAdvance = 3
First thread After arriveAndAwaitAdvance = 3
I hope that will answer your question.

Mehmet Mustafa Demir
- 87
- 1
- 3