Skip to content

Instantly share code, notes, and snippets.

@kpmeen
Last active December 8, 2017 10:04
Show Gist options
  • Save kpmeen/ecc463d9b510dfbc7daa510dcaae6ae6 to your computer and use it in GitHub Desktop.
Save kpmeen/ecc463d9b510dfbc7daa510dcaae6ae6 to your computer and use it in GitHub Desktop.
Converting a `java.util.concurrent.Future` into a `scala.concurrent.Future` using a blocking execution context
import java.util.concurrent.ExecutionException
import scala.concurrent.{ExecutionContext, ExecutionContextExecutor, Future}
import scala.concurrent.forkjoin.ForkJoinPool
import scala.util.Failure
object BlockingExecutor {
private[this] val threadCount = 5
private[this] implicit val executor: ExecutionContextExecutor =
ExecutionContext.fromExecutor(new ForkJoinPool(threadCount))
implicit def javaFuturetoScalaFuture[A](
jf: java.util.concurrent.Future[A]
): Future[A] = {
Future(jf.get()).transform {
case Failure(e: ExecutionException) => Failure(e.getCause)
case x => x
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment