/**Code copied and re-adapted  from  
 * http://www.ibm.com/developerworks/java/library/j-jtp11137.html and 
 * http://www.ibm.com/developerworks/java/library/j-jtp03048.html 
 */
package maxInParallel;

import jsr166y.ForkJoinTask;
import jsr166y.RecursiveAction;

public class MaxWithFJ extends RecursiveAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = -8358491434812907514L;
	private final SelectMaxProblem problem;
	private final int threshold;
	private int result;

	public MaxWithFJ(SelectMaxProblem subproblem, int threshold) {
		this.threshold = threshold;
		this.problem = subproblem;
	}

	@Override
	protected void compute() {
		if(problem.getSize() < threshold){
			result = problem.solveSequentially();
			System.out.println(Thread.currentThread()+" is solving sequentially on: "+ problem.getSize());
		}else{
				int midpoint = problem.getSize()/2;
				MaxWithFJ left = new MaxWithFJ(problem.subproblem(0, midpoint), threshold);
				MaxWithFJ right = new MaxWithFJ(problem.subproblem(midpoint+1, problem.getSize()), threshold);
				invokeAll(left, right);
				System.out.println("solving in parallel on: " + ForkJoinTask.getPool());
				result = Math.max(left.getResult(), right.getResult());
		}
		
	}

	public int getResult() {
		return result;
	}
	
}