Vert.x -- How to Execute Tasks/Methods in Parallel Using Future

528 views Asked by At

I'm new to Vert.x async programming. I want to know how I could run multiple tasks in parallel using futures. (Similar to this one using Java's callable).

The following is what I have but the tasks are being executed sequentially. What am I missing?

CompositeFuture.all(
                Future.future(h -> {
                        runTask("Future one");
                }),
                Future.future(h -> {
                        runTask("Future two");
                })
        ).onComplete(ar ->{
            if(ar.succeeded()){
                System.out.println("All succeeded");
            }
            else {
                System.out.println("At least one failed");
            }
        });

public static Future<Void> runTask(String m) {
        System.out.println("running " + m);

        System.out.println("30th fibonacci num is " + fib(30)); //Calling a method that calculates the nth fibonacci

        System.out.println("completed running " + m);

        return Future.<Void>succeededFuture();
    }

Output:
running Future one
Fib of 30 is 102334155
completed running Future one
running Future two
Fib of 30 is 102334155
completed running Future two
Done

But the expected output should be:
running Future one
running Future two
Fib of 30 is 102334155
Fib of 30 is 102334155
completed running Future one
completed running Future two
Done
Done

1

There are 1 answers

0
Alexey Soshin On

There are two problems with this code:

  1. Your fib() method is blocking.
  2. You're returning a future only after the blocking code was completed

Moreover, you didn't post it, but my guess it you're executing this from a main() method, which means Vert.x inherits the single main thread, that gets blocked.

Best solution would be to rewrite fib to return Future<Long> in the first place.