/*                          
 * 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 test.jp.co.scs.mbench.stub;

import jp.co.scs.mbench.BenchmarkTerminateException;
import jp.co.scs.mbench.component.BenchmarkSupport;

/**
 *      The stub for testing BenchmarkManager.
 *      This stub throws BenchmarkTerminateException.
 * 
 *      @author Tetsuro Ikeda
 */
public class StubBenchmarkManagerComponent3 extends BenchmarkSupport {

    private static int componentCount = 0;
    
    private static int terminateComponentID = 0;
    
    private static int terminateRepeatNumber = 0;
    
    private int currentRepeatNumber = 0;
    
    private boolean needTerminate = false;
    
    public static void setTerminateComponentID(int id) {
        terminateComponentID = id;
    }
    
    public static void setTerminateRepeatNumber(int number) {
        terminateRepeatNumber = number;
    }
    
    public StubBenchmarkManagerComponent3() {
        super();
        this.needTerminate = needTerminate();
    }
    
    public String[] execute() throws BenchmarkTerminateException {
        currentRepeatNumber++;
        if (this.needTerminate && (currentRepeatNumber >= terminateRepeatNumber)) {
            throw new BenchmarkTerminateException();
        } else {
            int minResponseTime = 10;
            int maxResoonseTime = 20;
            int actualResponseTime = minResponseTime +
                (int) ((maxResoonseTime - minResponseTime) * Math.random());
            try {
                Thread.sleep(actualResponseTime);
            } catch (InterruptedException ex) {
                // never come here
            }
            return null;
        }
    }
    
    private synchronized static boolean needTerminate() {
        if(componentCount++ == terminateComponentID) {
            return true;
        } else {
            return false;
        }
    }
}
