Vertx:executeBlocking() 与 Future。有什么不同?

Vertx 文档建议executeBlocking()在需要调用阻塞 API 时使用方法。另一方面,Vertx 还提供了一个 Future 的概念,它基本上做同样的事情。但该executeBlocking()方法不是静态的。它也不是 Future 的简单包装器,如果您查看它的实现,您会发现它非常复杂。这两者有什么区别?


假设我想以异步方式执行一些长时间运行的任务。这两种方法有什么区别吗?


方法一:


doTheJob() {

    Future<Void> future = Future.future();

    executeLongRunningBlockingOperation();

    future.complete();

    return future;

}


doTheJob().setHandler(asyncResult -> {

    // ... handle result

});

方法二:


vertx.executeBlocking(future -> {

    executeLongRunningBlockingOperation();

    future.complete();

}, res -> {

    // ... handle result

});


慕娘9325324
浏览 760回答 1
1回答

慕后森

您的第一个示例不是Future. 调用executeLongRunningBlockingOperation()将阻塞主线程,直到该方法完成——也就是说,在阻塞操作完成之前不会发生任何其他事情。在您的第二个示例中,阻塞调用被分拆到后台线程中,并且其他事情在它执行时继续发生。为了用更完整的示例说明这一点,此代码:public void executeLongRunningBlockingOperation() {&nbsp; &nbsp; Thread.sleep(5000);}public Future<Void> doTheJob() {&nbsp;&nbsp; &nbsp; System.out.println("Doing the job...");&nbsp; &nbsp; Future<Void> future = Future.future();&nbsp; &nbsp; executeLongRunningBlockingOperation();&nbsp; &nbsp; // this line will not be called until executeLongRunningBlockingOperation returns!&nbsp; &nbsp; future.complete();&nbsp; &nbsp; // nor will this method! This means that the method won't return until the long operation is done!&nbsp; &nbsp; return future;}public static void main(String[] args) {&nbsp; &nbsp; doTheJob().setHandler(asyncResult -> {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Finished the job");&nbsp; &nbsp; });&nbsp; &nbsp; System.out.println("Doing other stuff in the mean time...");}将产生以下输出:Doing the job...Finished the jobDoing other stuff in the mean time...而这段代码(使用executeBlocking):...public Future<Void> doTheJob() {&nbsp;&nbsp; &nbsp; System.out.println("Doing the job...");&nbsp; &nbsp; Future<Void> future = Future.future();&nbsp; &nbsp; Vertx vertx = Vertx.vertx();&nbsp; &nbsp; vertx.executeBlocking(call -> {&nbsp; &nbsp; &nbsp; &nbsp; executeLongRunningBlockingOperation();&nbsp; &nbsp; &nbsp; &nbsp; call.complete;&nbsp; &nbsp; }, result -> {&nbsp; &nbsp; &nbsp; &nbsp; // this will only be called once the blocking operation is done&nbsp; &nbsp; &nbsp; &nbsp; future.complete();&nbsp; &nbsp; });&nbsp; &nbsp; // this method returns immediately since we are not blocking the main thread&nbsp; &nbsp; return future;}...将产生:Doing the job...Doing other stuff in the mean time...Finished the job
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java