package utils;

/**
 * Title:        Barrier Synchronization
 * Description:
 *    Standard barrier synchronization
 *    Typically a Coordinator should instantiate the Barrier
 *    Each Worker joins the Barrier and is set free when all have joined
 * Copyright:    Copyright (c) 2003
 * Company:      UCF SEECS
 * @author Charles E. Hughes
 * @version 1.0
 */

public class Barrier {

  private int count;
  private int n;

  // Barrier Constructors
  // Default just coordinates one thread (rather meaningless)
  public Barrier() {
    this(1);
  }

  public Barrier (int count) {
    setCount(count);
  }

  // Set count of number of threads to coordinate
  public void setCount(int n) {
    this.n = n;
    count = n;
  }

  // Block at the barrier until all workers have joined
  // Critical Region -- Must be synchronized
  synchronized public void join() {
    count--;
    if (count > 0)
      try {
        wait();
      } catch (InterruptedException e) {System.out.println(e);}
    else {
      count = n;
      notifyAll();
    }
  }
}