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
There are two problems with this code:
fib()
method is blocking.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 returnFuture<Long>
in the first place.