0

FutureTaskの作業を理解しようとしています。私が読んだところでは、ExecutorServiceを使ってスレッドプールを作ることができます。後でRunnableまたはCallableFutureTaskにラップして実行することができます。その後、Futureオブジェクトを使用して結果を確認するか、タスクが実行中かどうかを確認できます。しかし、これは内部的にどのようにして行われますか?コレクションのFutureTaskは内部的にどのように動作しますか?

私が理解しようとしていることは、Callableインターフェイスを渡したときにシーンの後ろで起こることです。いくつか質問があります

  1. FutureTask自体がスレッドを内部的に実行してCallableコマンドの実行が終了したかどうかを定期的にチェックしていますか?もしそうでなければ、コマンドがいつ実行終了したかをどのように知っていますか?

  2. get()メソッドはどのように機能しますか? Callableインターフェイスから返される値はどのように取得されますか?

ドキュメントを見るとわかりませんでした。背後にあることを理解するために私が見ることができるコード例はありますか?

答えて

0

grepcodeのWebサイトを参照すると、回答が得られます。

AbstractExecutorServiceによって実装されるExecutorServiceインターフェイスは、以下のようにsubmit()メソッドを実装しています。 Executorため

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は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; 
    } 
ため execute方法

grepcodeの異なる実装を提供します

関連する問題