将Java Future转换为Scala Future [英] Convert a Java Future to a Scala Future

查看:165
本文介绍了将Java Future转换为Scala Future的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java Future对象,我想将其转换为Scala Future.

I have a Java Future object which I would like to convert into a Scala Future.

看看j.u.c.Future API,除了isDone方法之外,我没有什么可以使用的了.是isDone方法阻止了吗?

Looking at the j.u.c.Future API, there is nothing much that I could use other than the isDone method. Is this isDone method blocking?

目前这就是我的想法:

val p = Promise()
if (javaFuture.isDone())
  p.success(javaFuture.get)

有更好的方法吗?

推荐答案

只包装它怎么样(我假设这里有一个隐式的ExecutionContext):

How about just wrapping it (I'm assuming there's an implicit ExecutionContext here):

val scalaFuture = Future {
    javaFuture.get
}

一个简单的轮询策略可能看起来像这样(java.util.Future => F):

A simple polling strategy could look like this (java.util.Future => F):

def pollForResult[T](f: F[T]): Future[T] = Future {
    Thread.sleep(500)
    f
  }.flatMap(f => if (f.isDone) Future { f.get } else pollForResult(f))

这将检查Java未来是否每500毫秒完成一次.显然,总阻塞时间与上述相同(四舍五入至最接近的500ms),但是此解决方案将允许其他任务在ExecutionContext的同一线程中交错.

This will check if the Java future is done every 500ms. Obviously the total blocking time is the same as above (rounded up to the nearest 500ms) but this solution will allow other tasks to be interleaved in the same thread of the ExecutionContext.

这篇关于将Java Future转换为Scala Future的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆