strongdevil
strongdevil

Reputation: 83

java.lang.Thread cannot be cast to java.util.concurrent.ForkJoinWorkerThread

I am testing the Fibonacci example using RecursiveTask in Java SE 7 http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/RecursiveTask.html.

The program is as follows:

import java.util.concurrent.*;

public class testfuture{
    public static void main(String[] args) {
        System.out.println("Hello, World");
        Fibonacci fib = new Fibonacci(10);
        int result = fib.compute();
        System.out.println(result);
        }
}

class Fibonacci extends RecursiveTask<Integer> {
    final int n;
    Fibonacci(int n) { this.n = n; }
    public Integer compute() {
        if (n <= 1)
        return n;
        Fibonacci f1 = new Fibonacci(n - 1);
        f1.fork();
        Fibonacci f2 = new Fibonacci(n - 2);
        return f2.invoke() + f1.join();
    }
}

However, the program throws a run-time exception

Hello, World
Exception in thread "main" java.lang.ClassCastException: java.lang.Thread cannot be cast to java.util.concurrent.ForkJoinWorkerThread
    at java.util.concurrent.ForkJoinTask.fork(Unknown Source)
    at Fibonacci.compute(testfuture.java:21)
    at testfuture.main(testfuture.java:9)

I googled about this issue but could not figure out the problem.

Thanks for your help.

================

Solution:

public class testfuture{
    public static void main(String[] args) {
        System.out.println("Hello, World");
        Fibonacci fib = new Fibonacci(10);
        ForkJoinPool pool = new ForkJoinPool();
        int result = pool.invoke(fib);
        //int result = fib.compute(); //run-time exception
        System.out.println(result);
        }
}

Upvotes: 5

Views: 3717

Answers (2)

Aleksander Blomsk&#248;ld
Aleksander Blomsk&#248;ld

Reputation: 18552

You're creating a RecursiveAction, which is not supposed to be used with the fork-join framework. Instead you need to create a ForkJoinPool and let it execute your tasks

See for instance this article on an example of how to compute fibonacci using fork-join in Java.

Upvotes: 0

SLaks
SLaks

Reputation: 887449

You're misusing ForkJoinTask.

The point of ForkJoinTasks is to execute them within a ForkJoinPool.
The pool will call the compute() methods of the tasks for you in its ForkJoinWorkerThreads.

You should not call compute() directly.

Upvotes: 7

Related Questions