/*                          
 * mBench: The Open Source Micro Benchmark Tool 
 *                                             
 * Distributable under GPL license. 
 * See terms of license at gnu.org.                 
 *
 * Copyright (C) 2005 Sumisho Computer Systems Corp.
 */
package jp.co.scs.mbench;

/**
 *      Synchronizer
 * 
 *      @author Tetsuro Ikeda
 */
public class Synchronizer extends Thread {
    /**
     *  Flag for fist time
     */
    private boolean isFirst = true;
    
    /**
     *  Time of timeout
     */
    private long timeout = 120 * 1000;
    
    /**
     *  Sets the timeout.
     * 
     *  @param timeout timeout
     */
    public void setTimeout(long timeout) {
        this.timeout = timeout;
    }
    
    /**
     *  Gets the timeout.
     *  
     *  @return timeout (messure : ms)
     */
    public long getTimeout() {
        return this.timeout;
    }
    
    /**
     *  Synchronizes. The 1st caller get the lock of this object.
     *  The 2nd caller and later wait until the first caller release the lock.
     *  The 1st caller thread also become "wait mode" by using Thread#sleep method.
     *  So, it means you must not call this method directory (if you behave as first caller),
     *  and you must call Synchronizer#start method instead of this method.
     *  Synchronizer#start method creates a new thread and the thread only calls this method.
     *  You can do something todo, then call Synchronizer#interrupt method.
     *  It cause release of the lock, and let another caller (2nd one and later) go through
     *  the lock. These are designed to synchronize all benchmark container. 
     *  By the default setting, the timeout is occured in 60sec.
     */
    public void doSynchronize() {
        synchronized(this) {
            if (this.isFirst) {
                try {
                    Thread.sleep(this.timeout);
                    System.out.println("Synchronizer timtout " + this.timeout + "ms");
                } catch (InterruptedException ex) {
                    // ignore
                }
                this.isFirst = false;
            }
        }
    }
    
    /**
     *  just invoke the "doSynchronize"
     */
    public void run() {
        doSynchronize();
    }
}
