0

I am trying to understand the working of FutureTask in Collections. From what I read I understand you can create a thread pool using ExecutorService. Later you can wrap Runnable or Callable in FutureTask and execute it. After that you can use the Future object to check get the results or check if task is running. But how does this do internally ?

What I am trying to understand is what happens behind the scene when you pass a Callable interface. Few questions I have are

  1. Does the FutureTask itself runs a thread internally to constantly check if the Callable command has finished execution ? If not then how does it know when the command is finished execution?

  2. How does the get() method work? How does it get the value that is returned from the Callable interface ?

Looking at the documentation I couldn't figure out much. Is there any code example that I can look at to understand the behind the scenes.

krs8888
  • 1,239
  • 4
  • 19
  • 26

1 Answers1

0

Browse through grepcode website and you will get answers.

ExecutorService interface, which is implemented by AbstractExecutorService has below implementation for submit() method.

public <T> Future<T> submit(Callable<T> task) {
    if (task == null) throw new NullPointerException();
    RunnableFuture<T> ftask = newTaskFor(task);
    execute(ftask);
    return ftask;
}

protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
    return new FutureTask<T>(callable);
}

grepcode for Executor provides different implementations of execute method

grepcode for FutureTask

public FutureTask(Callable<V> callable) {
    if (callable == null)
        throw new NullPointerException();
    sync = new Sync(callable);
}


private final class Sync extends AbstractQueuedSynchronizer {
    Sync(Callable<V> callable) {
        this.callable = callable;
    }
}

public V get() throws InterruptedException, ExecutionException {
    return sync.innerGet();
} 

V innerGet() throws InterruptedException, ExecutionException {
        acquireSharedInterruptibly(0);
        if (getState() == CANCELLED)
            throw new CancellationException();
        if (exception != null)
            throw new ExecutionException(exception);
        return result;
    }
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211