Last active
August 8, 2018 05:15
-
-
Save evnm/6276017 to your computer and use it in GitHub Desktop.
Comparing approaches to convert `java.util.concurrent.Future`s to `com.twitter.util.Future`s.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.twitter.util.{Future => TwitterFuture, FuturePool} | |
import java.util.concurrent.{Future => JavaFuture} | |
/** | |
* Convert a Java Future to a Twitter Future. | |
*/ | |
def javaFutureToTwitterFuture[A](javaFuture: JavaFuture[A]): TwitterFuture[A] = | |
FuturePool.unboundedPool { javaFuture.get } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.twitter.util.{Future => TwitterFuture, _} | |
import java.util.concurrent.{Future => JavaFuture, TimeUnit} | |
/** | |
* Convert a Java Future to a Twitter Future. | |
*/ | |
def javaFutureToTwitterFuture[A]( | |
javaFuture: JavaFuture[A], | |
pollingInterval: Duration = Duration(50L, TimeUnit.MILLISECONDS) | |
): TwitterFuture[A] = { | |
val timer = new JavaTimer(isDaemon = false) | |
val promise = new Promise[A] { | |
timer.schedule(pollingInterval) { | |
if (javaFuture.isDone || javaFuture.isCancelled) { | |
timer.stop() | |
Try(javaFuture.get) match { | |
case Return(result) => setValue(result) | |
case Throw(t) => setException(t) | |
} | |
} | |
} | |
} | |
promise.setInterruptHandler { case _ => javaFuture.cancel(true) } | |
promise | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment