scalatwitter-util

Best way to convert a Java Future to a Twitter Future


In my application, I am converting a java.concurrent.future to a Twitter Future like so:

val myTwitterFuture = FuturePool.unboundedPool{ myJavaFuture.get}

Is this the correct way to do so, or is there a preferred method?


Solution

  • If your Java future is just a java.util.concurrent.Future, then what you have is basically the best you can do, because it's a very poor type. If you have a java.util.concurrent.CompletableFuture, you basically combine the answers to convert it to a scala.concurrent.Future and convert Scala future to a Twitter future:

    import java.util.concurrent.{Future => JFuture, CompletableFuture}
    import com.twitter.util.{Future => TwitterFuture, Promise => TwitterPromise}
    import scala.util.{Success, Failure}
    
    implicit class FutureWrapper[A](private val jf: JFuture[A]) extends AnyVal {
      def asTwitter: TwitterFuture[A] = jf match {
        case jf: CompletableFuture[A] =>
          val promise = new TwitterPromise[A]()
          jf.whenComplete { (result, exception) =>
            if (exception != null)
              promise.setException(exception)
            else
              promise.setValue(result)
          }
          promise
        case _ =>
          FuturePool.unboundedPool{ jf.get }
      }
    }