'How to capture command line input from Vert.x

Env: Mac OS 12.1, JDK 17, Vert.x 4.2.4

Question: how to capture command line input from a verticle? Tried so far following in the public void start(Promise<Void> startPromise) throws Exception method:

getVertx().createSharedWorkerExecutor("sys-in").executeBlocking(promise -> {
    try (final BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
        String line;
        int count = 0;
        do {
            System.out.print("message to MC: ");
            line = br.readLine();
            count++;
            //doSth(line); // e.g. send line over multicast
        } while (count < 3);
    } catch (Throwable t) {
        //   log.info("<start> ", t);
    } finally {
        //  bye(); // send a final message and close vertx
        promise.complete();
    }
});

This will start, get 3 nulls from br, and exit. Also tried a separated ExecutorService, in vain. Couldn't find any help in Vert.x doc either. Any hints are appreciated:

  • aware of the warnings of Vert.x when doing blocking stuff
  • Vert.x might not meant to be used this way, but would be cool if it (reading from command line) can be done with the same toolkit


Solution 1:[1]

I understand what you are trying to accomplish, but the problem is that that goes against fundamentals of verticles concept. Waiting for user input is potentially infinitely blocking operation i.e. there is no guarantee user will ever input the values. In that case, you are left with the verticle that is hung forever, spending resources and stuck in one spot. Multiply this if you are using worker verticles and you might have serious problems with the app. This issue is also emphasized here: https://vertx.io/docs/vertx-core/java/#blocking_code (under Warning).

In the link provided you can also find a suggested solution with a separate thread solution. Non-vertx thread won't mind being blocked and when the user input is provided can inform the vertx part of the application via the event bus that the user input dependent code can now be executed.

This might not be the solution you had in mind since it's not pure vertx, but have in mind that vert.x is just another tool, and that tool is not a good fit for what you are trying to accomplish here. However, it can be paired well with plain Java and it won't mind.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ph0enix