I’m very new to Vert.x and I decided to try it hoping that it offers Future api similar to Scala Future or even Cats/ZIO IO, but it seems that I cannot run multiple futures in parallel from my main function.
I figured out that by default they are run on a single threaded event loop, and it seems there is no way of specifying a custom event loop (Vertx instance) for the Future
to run. In their libraries (such as postgresql client) they use their internal api:
ContextInternal current = vertx.getOrCreateContext();
if (pipelined) {
return current.failedFuture("Cannot acquire a connection on a pipelined pool");
}
Promise<SqlConnectionPool.PooledConnection> promise = current.promise();
But from the application code I cannot use ContextInternal
, only Context
. Here is my code, I took it from the older question but changed it a little bit:
package com.example;
import io.vertx.core.*;
import io.vertx.core.impl.ContextInternal;
public class FuturesTest {
static Vertx vertx = Vertx.vertx();
public static long fib(int n) {
long a = 0, b = 1;
for (int i = 1; i < n; i++) {
var x = a;
a = b;
b = x + b;
}
return b;
}
public static Future<Void> runTask(String m) {
return Future.future(p -> {
System.out.println("running " + m);
p.complete();
}).map(p -> {
System.out.println("30th fibonacci num is " + fib(30)); //Calling a method that calculates the nth fibonacci
return null;
}).<Void>map(p -> {
System.out.println("completed running " + m);
return null;
}).onComplete(p -> System.out.println(m + " completed"));
}
public static void main(String[] args) throws Exception {
var f1 = runTask("Future one");
var f2 = runTask("Future two");
var ff = Future.any(f1, f2).onComplete(ar ->{
if(ar.succeeded()){
System.out.println("All succeeded");
} else {
System.out.println("At least one failed");
}
});
Thread.sleep(5000);
System.out.println("EXIT");
}
}
How can I run the future on the specified event loop from the application level?
I’m trying to achieve it purely with Futures, avoiding executeBlocking()
or similar methods but I haven’t found a way to change the default event loop to use multiple threads. I don’t want to create multiple event loops like in this question but make the Future
s run in the multiple threads.