new Thread(new Runnable() {
public void run() {
.............
.............
.............
}
}).start();
If i will do this in main it will create a new thread and will submit a task to it for asynchronous calculation.
If you see FutureTask documentation it also says:
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.
So how FutureTask
is an asynchronous computation
does it create thread internally and submit the task that we give it at the time of instantiating FutureTask
like:
FutureTask f = new FutureTask(new MyCallable());
Otherwise it can't be an asynchronous computation , please provide me the code snippet from the FutureTask
source code where it submits the task to thread, to make it asynchronous computation. Thanks.
I got the answer. 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:
When you call futureTask.run()
it just calls sync.innerRun();
and sync
is the instance of inner class Sync
. In that it just calls call()
on the callable object in the same thread.
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
}
}