Java Barrier

For the java.util.concurrent class see CyclicBarrier

A barrier is a type of synchronization method. A barrier for a group of threads or processes in the source code means any thread/process must stop at this point and cannot proceed until all other threads/processes reach this barrier.[1]

The basic Java synchronization mechanism centers on the keyword synchronized, which predicates methods. In java, all objects can be used like monitors (protected types).

That means that given an object A, no more than one thread can execute a synchronized method of A at any time.

  • Barrier implementation
/*
 * Given object A, no more than one thread can execute a synchronized
   method of A at any time.
 */
public class Barrier
{
    public synchronized void block() throws InterruptedException
    {
        wait();
    }
 
    public synchronized void release() throws InterruptedException
    {
        notify();
    }
 
    public synchronized void releaseAll() throws InterruptedException
    {
        notifyAll();
    }
 
}

And an example with two threads.

class BarrierExample 
{
 
    static class MyThread1 implements Runnable
    {
        public MyThread1(Barrier barrier)
        {
            this.barrier = barrier;
        }
 
        public void run()
        {
            try
            {
                Thread.sleep(1000);
                System.out.println("MyThread1 waiting on barrier");
                barrier.block();
                System.out.println("MyThread1 has been released");
            } catch (InterruptedException ie)
            {
                System.out.println(ie);
            }
        }
 
        private Barrier barrier;
 
    }
 
    static class MyThread2 implements Runnable
    {
        Barrier barrier;
 
        public MyThread2(Barrier barrier)
        {
            this.barrier = barrier;
        }
 
        public void run()
        {
            try
            {
                Thread.sleep(3000);
                System.out.println("MyThread2 releasing blocked threads\n");
                barrier.release();
                System.out.println("MyThread1 releasing blocked threads\n");
            } catch (InterruptedException ie)
            {
                System.out.println(ie);
            }
        }
    }
 
    public static void main(String[] args) throws InterruptedException
    {
        /*
         *     MyThread1            MyThread2
         *         ...                    ...
         *         BR.block();            ...
         *         ...                    BR.release();
         */
        Barrier BR = new Barrier();
        Thread t1 = new Thread(new BarrierExample.MyThread1(BR));
        Thread t2 = new Thread(new BarrierExample.MyThread2(BR));
        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }
}
Bibliography
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.