Vertxのドキュメントでは、executeBlocking()
ブロッキングAPIを呼び出す必要がある場合にメソッドを使用することを提案しています。一方、Vertxは、基本的に同じことを行うFutureの概念も提供します。しかし、executeBlocking()
メソッドは静的ではありません。また、Futureの単純なラッパーではなく、その実装を見ると、かなり複雑であることがわかります。これら2つの違いは何ですか?
長時間実行されるタスクを非同期で実行したいとします。これら2つの方法に違いはありますか?
方法1:
doTheJob() {
Future<Void> future = Future.future();
executeLongRunningBlockingOperation();
future.complete();
return future;
}
doTheJob().setHandler(asyncResult -> {
// ... handle result
});
方法2:
vertx.executeBlocking(future -> {
executeLongRunningBlockingOperation();
future.complete();
}, res -> {
// ... handle result
});
最初の例は、の正しい使用法ではありませんFuture
。toexecuteLongRunningBlockingOperation()
を呼び出すと、そのメソッドが完了するまでメインスレッドがブロックされます。つまり、ブロック操作が完了するまで、他に何も起こりません。2番目の例では、ブロッキング呼び出しがバックグラウンドスレッドにスピンオフされ、実行中に他のことが発生し続けます。
より完全な例でこれを説明するために、次のコードを使用します。
public void executeLongRunningBlockingOperation() {
Thread.sleep(5000);
}
public Future<Void> doTheJob() {
System.out.println("Doing the job...");
Future<Void> future = Future.future();
executeLongRunningBlockingOperation();
// this line will not be called until executeLongRunningBlockingOperation returns!
future.complete();
// nor will this method! This means that the method won't return until the long operation is done!
return future;
}
public static void main(String[] args) {
doTheJob().setHandler(asyncResult -> {
System.out.println("Finished the job");
});
System.out.println("Doing other stuff in the mean time...");
}
次の出力が生成されます。
Doing the job...
Finished the job
Doing other stuff in the mean time...
一方、このコード(executeBlockingを使用):
...
public Future<Void> doTheJob() {
System.out.println("Doing the job...");
Future<Void> future = Future.future();
Vertx vertx = Vertx.vertx();
vertx.executeBlocking(call -> {
executeLongRunningBlockingOperation();
call.complete;
}, result -> {
// this will only be called once the blocking operation is done
future.complete();
});
// this method returns immediately since we are not blocking the main thread
return future;
}
...
生成されます:
Doing the job...
Doing other stuff in the mean time...
Finished the job
Vert.xの理解を深めたい場合は、次のハンズオンチュートリアルをお勧めします。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加