Vert.x仍然阻止EventLoop,即使在executeBlocking中运行了阻塞代码

问题描述 投票:0回答:1

我有代码:

public static void main(String[] args) {
    Vertx.vertx().deployVerticle("com.my.domain.app.Server"); //Server.java
}
public void start() {
    Router router = Router.router(vertx);
    router.route("/hello").handler(event -> {
        vertx.executeBlocking(onDone -> {
            try {
                Thread.sleep(5000); //long operation
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            onDone.complete();
        }, onDone -> {
            event.response().end();
        });
    });
    vertx.createHttpServer()
            .requestHandler(router)
            .listen(8080);
}

然后我在浏览器中运行8个选项卡并调用:localhost:8080/hello。5秒后完成前4个标签页。 (因为线程处于睡眠状态),则在10秒后再发送4。

因此,每(4个)EventLoop被阻止,直到作业完成。为什么?我正在executeBlocking方法中运行代码。

编辑:

SOLUTION:我找到了答案。答案是

router.route("/hello").blockingHandler(event -> {...

Vert.x中的示例:https://github.com/vert-x3/vertx-examples/blob/master/web-examples/src/main/java/io/vertx/example/web/blockinghandler/Server.java

multithreading vert.x nonblocking reactive event-loop
1个回答
0
投票

我想,您获得的效果(在您的初始代码中)是由于阻止任务执行的默认ordered模式。

如果您使用其他executeBlocking方法,并将有序参数设置为false,我想,您将获得与您的工作线程池大小成比例的并发-您需要什么。

通过使用executeBlocking而不使用有序参数,您已将有序设置隐式设置为true。因此,每个事件循环线程(我想)将在单个上下文中处理调用,这将坚持(由于排序)到单个工作线程。因此,您将有效地运行4个并发的阻塞任务-您所观察到的。不使用其他辅助线程。

© www.soinside.com 2019 - 2024. All rights reserved.