Skip to content

Commit 1303533

Browse files
tomekl007pedja4
authored andcommitted
Bael 883 phaser (eugenp#1794)
* BAEL-883 Code for the Phaser * BAEL-883 remove comments
1 parent b5f816a commit 1303533

2 files changed

Lines changed: 68 additions & 0 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.baeldung.concurrent.phaser;
2+
3+
import java.util.concurrent.Phaser;
4+
5+
class LongRunningAction implements Runnable {
6+
private String threadName;
7+
private Phaser ph;
8+
9+
LongRunningAction(String threadName, Phaser ph) {
10+
this.threadName = threadName;
11+
this.ph = ph;
12+
ph.register();
13+
}
14+
15+
@Override
16+
public void run() {
17+
System.out.println("This is phase " + ph.getPhase());
18+
System.out.println("Thread " + threadName + " before long running action");
19+
ph.arriveAndAwaitAdvance();
20+
try {
21+
Thread.sleep(20);
22+
} catch (InterruptedException e) {
23+
e.printStackTrace();
24+
}
25+
ph.arriveAndDeregister();
26+
}
27+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.baeldung.concurrent.phaser;
2+
3+
import org.junit.FixMethodOrder;
4+
import org.junit.Test;
5+
import org.junit.runners.MethodSorters;
6+
7+
import java.util.concurrent.ExecutorService;
8+
import java.util.concurrent.Executors;
9+
import java.util.concurrent.Phaser;
10+
11+
import static junit.framework.TestCase.assertEquals;
12+
13+
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
14+
public class PhaserTest {
15+
16+
@Test
17+
public void givenPhaser_whenCoordinateWorksBetweenThreads_thenShouldCoordinateBetweenMultiplePhases() {
18+
//given
19+
ExecutorService executorService = Executors.newCachedThreadPool();
20+
Phaser ph = new Phaser(1);
21+
assertEquals(0, ph.getPhase());
22+
23+
//when
24+
executorService.submit(new LongRunningAction("thread-1", ph));
25+
executorService.submit(new LongRunningAction("thread-2", ph));
26+
executorService.submit(new LongRunningAction("thread-3", ph));
27+
28+
//then
29+
ph.arriveAndAwaitAdvance();
30+
assertEquals(1, ph.getPhase());
31+
32+
//and
33+
executorService.submit(new LongRunningAction("thread-4", ph));
34+
executorService.submit(new LongRunningAction("thread-5", ph));
35+
ph.arriveAndAwaitAdvance();
36+
assertEquals(2, ph.getPhase());
37+
38+
39+
ph.arriveAndDeregister();
40+
}
41+
}

0 commit comments

Comments
 (0)