2016-05-04 7 views
3

CompletableFuture APIはかなり威圧的です。たくさんのことが受け入れられています。さまざまなオプションがなぜ存在するのかを知ることは難しいです。ブロックしないでCompletableFutureを開始するにはどうしたらいいですか?

CompletableFuture<?> future = CompletableFuture.supplyAsync(() ->..., executor) 

future.startNonBlocking...((...) -> { callback behavior done when complete } 

私は基本的になく、などの優れたスレッドプーリング、エラー処理、とnew Thread(() -> dostuff).start()を模倣注意しようとしている:私は実際にここにRunnableインタフェースを必要としない、私は、既存のコードの一部をgenerifyingよ。

私の非同期タスクを開始し、完了したら動作を実行する正しい方法は何ですか?またはスローされた例外を処理しますか?ここで

+0

http://www.nurkiewicz.com/2013/05/java-8-definitive-guide-to.html –

答えて

2

は、単純な非同期コールバックです:

CompletableFuture.supplyAsync(() -> [result]).thenAccept(result -> [action]); 

それとも、エラー処理が必要な場合:

CompletableFuture.supplyAsync(() -> [result]).whenComplete((result, exception) -> { 
    if (exception != null) { 
     // handle exception 
    } else { 
     // handle result 
    } 
}); 
2
new Thread(() -> dostuff).start() 

あなたが

を使用することができますので、 dostuffは、 Runnableをを実装していることを意味し
static CompletableFuture<Void> runAsync(Runnable runnable)  
static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor) 

でも。

関連する問題