Skip to main content

Phaser demo

package com.javahowdoi.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Phaser;

import static junit.framework.TestCase.assertEquals;

public class PhaserDemo {
    private static class PhaserTask implements Runnable {
        private Phaser p;

        PhaserTask(Phaser p) {
            this.p = p;
            // register the current task as new party to the barrier
            p.register();
        }

        @Override
        public void run() {
            // deregisters the current task from the barrier
            // optionally the task can wait for all threads to arrive at the barrier
             p.arriveAndDeregister();
            //System.out.println("Exiting thread now");
        }
    }
    public static void main(String[] args) {
        Phaser p = new Phaser();
        p.register();
        assertEquals("In Phase 1", 0, p.getPhase());
        ExecutorService es = Executors.newFixedThreadPool(3);
        es.submit(new PhaserTask(p));
        es.submit(new PhaserTask(p));
        // wait for all threads to arrive at the barrier
        p.arriveAndAwaitAdvance();
        // Phase count is incremented once all parties arrive at the barrier
        // this allows the Phaser object to be reused over multiple phases of execution
        assertEquals("In Phase 1", 1, p.getPhase());
        es.submit(new PhaserTask(p));
        es.submit(new PhaserTask(p));
        p.arriveAndAwaitAdvance();
        assertEquals("In Phase 2", 2, p.getPhase());
        p.arriveAndDeregister();
        assertEquals("Registered parties 0", 0, p.getRegisteredParties() );
        es.shutdown();
    }
}

Comments