I have to use Java Recursive Task (Fork and Join)
to calculate something like this: (3*3)^2.
I have this code which is supposed to work:
public class ForkJoin1 extends RecursiveTask<Long> {
int num;
public ForkJoin1 (int num) {
this.num = num;
}
@Override
protected Long compute() {
if(num == 0) return Long.valueOf(1);
ForkJoin1 fj1 = new ForkJoin1(num*num);
ForkJoin1 fj2 = new ForkJoin1((int) Math.pow(num, 2));
fj1.fork();
return fj1.compute() + fj2.join();
}
public static void main (String[] args) {
ForkJoinPool pool = new ForkJoinPool();
System.out.println("Result: " + pool.invoke(new ForkJoin1(3)));
}
}
However, when I run it, I get this error:
What am I doing wrong?
Please, note that I'm new at Recursivetask in Java.
Your code calls
compute
withnum = 3
,so you create a new object and call
compute
withnum = 9 (3 * 3)
,so you create a new object and call
compute
withnum = 81 (9 * 9)
,so you create a new object and call
compute
withnum = 6561 (81 * 81)
,so you create a new object and call
compute
withnum = 43046721 (6561 * 6561)
,so you create a new object and call
compute
withnum = -501334399 (43046721 * 43046721)
,...
Oops, numeric overflow. Well it continues anyway, with
num
having the following values, from the beginning:As you can see,
num
never becomes0
, so the calls never stop.