How to run infinite loop on vertx using while() loop

别等时光非礼了梦想. 提交于 2019-12-13 01:04:51

问题


I would like to run an infinite loop on verx on diff thread. Should be something like this:

vertx.executeBlocking(future -> {
while(true){
}
   //some logic (e.g waiting on blocking-code)
}

thing is that on vertx even for executeBlocking threads you have global timeout which you can increase. but I would like to set for this execution non-timeout warnings as it will run forever

  1. am I achieving my purpose right with vertx?
  2. In case 1 is true. how to exclude this specific blocking execution from the timeout warnings

回答1:


I have a similar use case, when I need to consume a blocking api, I have used the following code

@Override
public void start() {
    vertx.<Void>executeBlocking(f -> {
        while (true) {
            // blocking...
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            vertx.eventBus().publish("channel.1", "msg");
        }
    }, voidAsyncResult -> System.out.println("done"));
}



回答2:


You don't.

If you have a condition that triggers processing, the have the processing happen at that point and not inside an infinite loop.

Example:

while ((event = eventQueue.take()) != null) {
  final Vertx target = event.target;
  executor.submit(() -> { 
    doProcessing(target);
  });
}

The main reason for this is that even threads in a blocking state do consume resources. If you have 1000 threads waiting on events, then the system is significantly wasting time on thread-scheduling. This is why all modern IO processing happens non-blocking, in a similar fashion as the code above.



来源:https://stackoverflow.com/questions/47709391/how-to-run-infinite-loop-on-vertx-using-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!