scalafuturescala-java-interop

Convert a Java Future to a Scala Future


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

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?

Currently this is what I have in my mind:

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

Is there a better way to do this?


Solution

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

    val scalaFuture = Future {
        javaFuture.get
    }
    

    EDIT:

    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))
    

    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.