ListenableFuture to scala Future

断了今生、忘了曾经 提交于 2019-12-03 08:17:38

问题


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 ?


回答1:


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



回答2:


Another, slightly shorter solution:

implicit class ListenableFutureDecorator[T](val f: ListenableFuture[T]) extends AnyVal {
  def asScala(implicit e: Executor): Future[T] = {
    val p = Promise[T]()
    f.addListener(() => p.complete(Try(f.get())), implicitly[Executor])
    p.future
  }
}


来源:https://stackoverflow.com/questions/18026601/listenablefuture-to-scala-future

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!