title: How FutureTask is asynchronous computation
body: <pre><code>new Thread(new Runnable() {
             public void run() {
                   .............
                   .............
                   .............
      }
  }).start();
  </code></pre>
  
  <p>If i will do this in main it will create a new thread and will submit a task to it for asynchronous calculation.</p>
  
  <p>If you see FutureTask <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/FutureTask.html">documentation</a> it also says:</p>
  
  <blockquote>
    <p>A cancellable asynchronous computation. This class provides a base
    implementation of Future, with methods to start and cancel a
    computation, query to see if the computation is complete, and retrieve
    the result of the computation.</p>
  </blockquote>
  
  <p>So how <code>FutureTask</code> is an <strong><code>asynchronous computation</code></strong> does it create thread internally and submit the task that we give it at the time of instantiating <code>FutureTask</code> like:</p>
  
  <pre><code>FutureTask f = new FutureTask(new MyCallable());
  </code></pre>
  
  <p>Otherwise it can't be an asynchronous computation , please provide me the code snippet  from the <code>FutureTask</code> <a href="http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/FutureTask.java">source code</a>  where it submits the task to thread, to make it asynchronous computation. Thanks.</p>
  
  <hr>
  
  <p><strong>I got the answer.</strong> It's is basically trying to run the task in the same thread as that of caller. It is pretty evident in the given code:</p>
  
  <p>When you call <code>futureTask.run()</code> it just calls <code>sync.innerRun();</code> and <code>sync</code> is the instance of inner class <code>Sync</code>. In that it just calls <code>call()</code> on the callable object in the same thread.</p>
  
  <pre><code>void innerRun() {
          if (!compareAndSetState(READY, RUNNING))
              return;
  
          runner = Thread.currentThread(); //here it is getting the current thread
          if (getState() == RUNNING) { 
              V result;
              try {
                  result = callable.call();//here calling call which executes in the caller thread.
              } catch (Throwable ex) {
                  setException(ex);
                  return;
              }
              set(result);
          } else {
              releaseShared(0); // cancel
          }
      }
  </code></pre>