I've just read the javadoc about Phaser
there and have a question about usage that class. The javadoc provides a sample, but what about real-life example? Where such a barrier implementation could be useful in practise?
Asked
Active
Viewed 506 times
1

user3663882
- 6,957
- 10
- 51
- 92
-
Have you seen this article - http://examples.javacodegeeks.com/core-java/util/concurrent/phaser/java-util-concurrent-phaser-example/ . ? It describes pretty well the adventages and used cases of Phaser. – vtor Feb 22 '15 at 15:11
-
The article hardly goes beyond what the javadoc exposes and the example is far from being real-world. – h7r Dec 27 '15 at 16:46
1 Answers
1
I've not used Phaser
, but I have used CountDownLatch
. The referenced docs says:
[
Phaser
is] similar in functionality to ...CountDownLatch
but supporting more flexible usage.
CountDownLatch
is useful anywhere where you fire off multiple threads to do some tasks, and in old-school you would have used Thread.join()
to wait for them to finish.
For example:
Old School:
Thread t1 = new Thread("one");
Thread t2 = new Thread("two");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Both threads have finished");
Using CountDownLatch
public class MyRunnable implement Runnable {
private final CountDownLatch c; // Set this in constructor
public void run() {
try {
// Do Stuff ....
} finally {
c.countDown();
}
}
}
CountDownLatch c = new CountDownLatch(2);
executorService.submit(new MyRunnable("one", c));
executorService.submit(new MyRunnable("two", c));
c.await();
System.out.println("Both threads have finished");

Stewart
- 17,616
- 8
- 52
- 80
-
1Your answer is off the topic. OP asked specifically about Phaser, not about CountDownLatch. – coberty Jan 03 '17 at 10:48
-
The OP asked about "the barrier pattern" and for real-life examples. `CountDownLatch` is indeed an implementation of that, and my example is cut down from real-life code. – Stewart Jan 04 '17 at 11:55
-
Are you down on people providing help or something? YOU read the question again. The question asks for an example of the barrier pattern. There are no other answers. Maybe my answer doesn't meet your super-perfect exacting standards, but I do think it qualifies as "useful", which is the only criteria for up- or down-votes. – Stewart Jan 04 '17 at 23:02
-
1OP asked specifically about real-life example of Phaser barrier. So your answer is not useful at all. EOT from my side. – coberty Jan 05 '17 at 09:49