java - vertxexecute阻止不同的行为

标签 java multithreading asynchronous vert.x

我正在尝试使用 vertxexecuteBlocking 来模拟我执行的实时场景

vertx.setPeriodic(1000, id ->{
    counter += 1;
    LOGGER.info("invoked method {} ",counter);
    vertx.executeBlocking(future -> {
        int counterFinal = counter;
        String result = service.blockingMethod("cycle "+counterFinal+" executed");
        future.complete(result);
    }, res -> {
        LOGGER.info(String.format("The result is: %s", res.result()));
    });

阻止方法非常简单

public String blockingMethod(String result){
    block(2);
    return result;
}

这就是结果

07:50:27.742 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.AsyncExperimentalVerticle - invoked method 1 
07:50:28.742 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.AsyncExperimentalVerticle - invoked method 2 
07:50:29.740 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.AsyncExperimentalVerticle - invoked method 3 
07:50:29.764 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.AsyncExperimentalVerticle - The result is: cycle 1 executed
07:50:30.739 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.AsyncExperimentalVerticle - invoked method 4 
07:50:31.739 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.AsyncExperimentalVerticle - invoked method 5 
07:50:31.773 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.AsyncExperimentalVerticle - The result is: cycle 3 executed
07:50:32.751 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.AsyncExperimentalVerticle - invoked method 6 
07:50:33.748 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.AsyncExperimentalVerticle - invoked method 7 
07:50:33.789 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.AsyncExperimentalVerticle - The result is: cycle 5 executed

由于延迟设置为 2 秒,因此显然平均丢失了两个事件。 然后我将阻塞方法包装在一个类中,然后按以下方式执行

vertx.setPeriodic(1000, id ->{
    counter++;
    LOGGER.info("invoked method {} ",counter);
    service.wrapperMethod("Hello", counter, new Handler<AsyncClass>() {
        @Override
        public void handle(AsyncClass event) {
            vertx.executeBlocking(future -> {
                String result = event.result();
                future.complete(result);
            }, res -> {
                LOGGER.info(String.format("The result is: %s", res.result()));
            });
        }
    });
});

包装方法就是这样设计的

public void wrapperMethod(String input, int cycle, Handler<AsyncClass> execute) {
    AsyncClass instance = new AsyncClass(input,String.valueOf(cycle)); // my custom class where the result method has a 2 sec delay
    execute.handle(instance);
}

然后我得到了预期的结果。

08:08:27.358 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.TestVerticle2 - invoked method 1 
08:08:27.368 [vert.x-worker-thread-0] INFO lab.async.base.support.AsyncClass - Invoking method inside AsyncClass class
08:08:28.338 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.TestVerticle2 - invoked method 2 
08:08:29.345 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.TestVerticle2 - invoked method 3 
08:08:29.384 [vert.x-worker-thread-0] INFO lab.async.base.support.AsyncClass - Invoking method inside AsyncClass class
08:08:29.386 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.TestVerticle2 - The result is: Hello world of cycle 1
08:08:30.347 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.TestVerticle2 - invoked method 4 
08:08:31.351 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.TestVerticle2 - invoked method 5 
08:08:31.391 [vert.x-worker-thread-0] INFO lab.async.base.support.AsyncClass - Invoking method inside AsyncClass class
08:08:31.391 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.TestVerticle2 - The result is: Hello world of cycle 2
08:08:32.341 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.TestVerticle2 - invoked method 6 
08:08:33.343 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.TestVerticle2 - invoked method 7 
08:08:33.396 [vert.x-worker-thread-0] INFO lab.async.base.support.AsyncClass - Invoking method inside AsyncClass class
08:08:33.397 [vert.x-eventloop-thread-0] INFO lab.async.base.verticle.TestVerticle2 - The result is: Hello world of cycle 3

现在我看到异步执行没有错过任何一个事件。我找不到可能的解释。 即使在包装器方法中,如果我给出 n 秒的延迟,它也会按预期错过事件。

请有人帮助我理解这种行为。

更新1:

对于第二种情况,AsyncClass 的结构如下所示

public class AsyncClass {

    private static final Logger LOGGER = LoggerFactory.getLogger(AsyncClass.class);

    private String input;
    private String cycle;

    public AsyncClass(String input, String cycle) {
        this.input = input;
        this.cycle = cycle;
    }

    public String result(){
        LOGGER.info("Invoking method inside AsyncClass class");
        block(2);
        return input+" world of cycle "+cycle;
    }

    private void block(int pauseLimitInSecond){
        try {
            TimeUnit.SECONDS.sleep(pauseLimitInSecond);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            LOGGER.error("exception - > ", e);
        }
    }
}

最佳答案

观察到的行为是由于 Lambda body variable capture其中捕获外部类引用 ( this )。

外部类实例变量counter当计算Lambda主体表达式时,它的值会发生变化(在初始值的基础上增加1),这会产生意外行为的错觉。

保持相同的程序顺序,您可以将Lambda表达式主体替换为 Handler<Future<String>>实现地点counter外部实例变量存储在另一个实例变量中,该变量将在处理程序执行主体中使用:

private static final class BlockingHandler implements Handler<Future<String>> {

    private final YourBlockingService service;

    private final int counter;

    public BlockingHandler(int counter, YourBlockingService service) {
        this.counter = counter;
        this.service = service;
    }

    @Override
    public void handle(Future<String> event) {
        String result = service.blockingMethod("cycle " + this.counter + " executed", 2);
        event.complete(result);
    }
}

您的 verticle 代码将如下所示:

this.vertx.setPeriodic(
      1000,
      id -> {
          counter += 1;
          LOGGER.info("invoked method {}", counter);
          vertx.executeBlocking(
                new YourBlockingHandler(this.counter, this.service),
                res -> LOGGER.info(String.format("The result is: %s", res.result()))
          );
      }
);

再说一遍,上述行为仅与闭包语义相关,与Vert.x内部无关。

关于java - vertxexecute阻止不同的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50500258/

相关文章:

java - 如何在java中导入证书?

java - 什么是计算所有值的总和超过 double 限制的平均值的好解决方案?

c - GDB和C的多线程调试教程

java - 与信号量同步线程

javascript - 如何做出 JSON.parse promise ? (或异步)

Java Instant.parse on Date java 8

java - 请放心 : handling multiple results in response?

ios - 让所有端点等待一个确切的端点

java - 如何使用 Unirest 并行发送多个异步请求

javascript - Javascript 中嵌套函数 "Class"结构中的变量范围