Without block if delay == 2
it works, but doesn't work with it.
Here's ForkJoin's compute:
compute() {
if(lastElem - firstElem == 1)
return array[firstElem];
if(lastElem - firstElem == 2){
if(array[firstElem] > array[lastElem])
return array[firstElem];
else
return array[lastElem];
}
int midElem = (firstElem + lastElem) / 2;
MyForkJoinTask left = new MyForkJoinTask(array, firstElem, midElem);
MyForkJoinTask right = new MyForkJoinTask(array, midElem, lastElem);
left.fork();
right.fork();
int leftResult = left.join();
int rightResult = right.join();
if(leftResult > rightResult)
return leftResult;
else
return rightResult;
}
Here's my main method:
main(String[] args) {
Random r = new Random();
for(int i = 0; i < array.length; i++){
array[i] = r.nextInt();
}
MyForkJoinTask root = new MyForkJoinTask(array);
F_J_POOL.submit(root);
System.out.println("Result is " + root.join());
}
Short error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at com.bg.fork_join.MainFJ.main(MainFJ.java:24) Caused by: java.lang.ArrayIndexOutOfBoundsException ... 15 more
Caused by: java.lang.ArrayIndexOutOfBoundsException: 10000 at com.bg.fork_join.MyForkJoinTask.compute(MyForkJoinTask.java:31)
Could you show me where the problem is?
I don't know anything about ForkJoin
, but this looks suspicious just on general principles:
if(lastElem - firstElem == 2){
if(array[firstElem] > array[lastElem])
return array[firstElem];
else
return array[lastElem];
}
The rest of your code makes it appear that you're processing a subarray from firstElem
(inclusive) to lastElem
(exclusive), so shouldn't you be using lastElem-1
to index?