title: java.lang.Thread cannot be cast to java.util.concurrent.ForkJoinWorkerThread
body: <p>I am testing the Fibonacci example using RecursiveTask in Java SE 7 <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/RecursiveTask.html" rel="nofollow">http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/RecursiveTask.html</a>.</p>
  
  <p>The program is as follows:</p>
  
  <pre><code>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&lt;Integer&gt; {
      final int n;
      Fibonacci(int n) { this.n = n; }
      public Integer compute() {
          if (n &lt;= 1)
          return n;
          Fibonacci f1 = new Fibonacci(n - 1);
          f1.fork();
          Fibonacci f2 = new Fibonacci(n - 2);
          return f2.invoke() + f1.join();
      }
  }
  </code></pre>
  
  <p>However, the program throws a run-time exception</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>I googled about this issue but could not figure out the problem.</p>
  
  <p>Thanks for your help.</p>
  
  <p>================</p>
  
  <p>Solution:</p>
  
  <pre><code>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);
          }
  }
  </code></pre>