简体   繁体   中英

Error when trying to calculate (3*3)^2 using Recursive Task (Fork and Join) in Java

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 with num = 3 ,
so you create a new object and call compute with num = 9 (3 * 3) ,
so you create a new object and call compute with num = 81 (9 * 9) ,
so you create a new object and call compute with num = 6561 (81 * 81) ,
so you create a new object and call compute with num = 43046721 (6561 * 6561) ,
so you create a new object and call compute with num = -501334399 (43046721 * 43046721) ,
...

Oops, numeric overflow . Well it continues anyway, with num having the following values, from the beginning:

3
9
81
6561
43046721
-501334399
2038349057
-1970898431
120648705
1995565057
-1876701183
-1454923775
1989099521
2099150849
977076225
1954152449
-386662399
-773324799
-1546649599
1201668097
-1891631103
511705089
1023410177
2046820353
-201326591
-402653183
-805306367
-1610612735
1073741825
-2147483647
1
1
1
1
1
...

As you can see, num never becomes 0 , so the calls never stop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM