user3663882
user3663882

Reputation: 7367

Where to use barrier pattern in java?

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?

Upvotes: 1

Views: 539

Answers (1)

Stewart
Stewart

Reputation: 18303

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");

Upvotes: 1

Related Questions