I am in the process of writing a small scala wrapper around a java library.
The java library has an object QueryExecutor exposing 2 methods:
- execute(query): Result
- asyncExecute(query): ListenableFuture[Result]
ListenableFuture in this context is the one from the guava library.
I want my scala wrapper to return a Future[Result] instead of the java object, but I am not sure what is the best way to implement that. Here are 2 solutions I came up with:
future {
executor.execute(query)
}
and
val p = promise[Result]
val guavaFuture = executor.asyncExecute(query)
Futures.addCallback(guavaFuture, new FutureCallback[Result] {
def onFailure(t: Throwable) {
p.failure(t)
}
def onSuccess(result: Result) {
p.success(result)
}
})
p.future
I am wondering which method is the best. My intuition is that the first one, while returning a Future, will still block a thread while the call to execute waits for a response, the second one looks like it should be really non blocking. Any comment on the pros/cons of each method ?
ExecutionContext
consists of 4 workers. Eachfuture { executor.execute(query) }
blocks 1 worker, so 4 "futures" will block your program entirely. You could create additionalExecutionContext
for blocking operations, but there would be some overhead. – Vtarj