问题描述
我正在围绕Java库编写一个小的Scala包装器.
I am in the process of writing a small scala wrapper around a java library.
java库中有一个对象QueryExecutor,它公开了2种方法:
The java library has an object QueryExecutor exposing 2 methods:
- 执行(查询):结果
- asyncExecute(query):ListenableFuture [Result]
ListenableFuture在此上下文中是番石榴库中的那个.
ListenableFuture in this context is the one from the guava library.
我希望我的Scala包装器返回Future [Result]而不是java对象,但是我不确定实现该目标的最佳方法是什么.这是我想出的2种解决方案:
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)
}
和
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
我想知道哪种方法是最好的.我的直觉是,第一个在返回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 ?
推荐答案
第二个选项是最好的,它可以使所有内容保持异步.但是...您可以做得更好,并将解决方案抽象为可重用的模式:
The second option is best, it keeps everything asynchronous. but... you can do one better and abstract the solution into a reusable pattern:
implicit class RichListenableFuture[T](lf: ListenableFuture[T]) {
def asScala: Future[T] = {
val p = Promise[T]()
Futures.addCallback(lf, new FutureCallback[T] {
def onFailure(t: Throwable): Unit = p failure t
def onSuccess(result: T): Unit = p success result
})
p.future
}
}
然后您可以简单地致电:
You can then simply call:
executor.asyncExecute(query).asScala
这篇关于未来Scala的未来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!