Skip to content

Instantly share code, notes, and snippets.

@nelanka
Created February 28, 2015 12:45
Show Gist options
  • Save nelanka/e0ca3348707900467415 to your computer and use it in GitHub Desktop.
Save nelanka/e0ca3348707900467415 to your computer and use it in GitHub Desktop.
Timeout Future
import java.util.concurrent.{Executors, TimeoutException}
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.concurrent.ExecutionContext.Implicits.global
def timeoutFuture[T](f: Future[T], after: Duration)(implicit ec: ExecutionContext) = {
val p = Promise[T]()
p tryCompleteWith f
val action = new Runnable {
override def run(): Unit = p tryFailure new TimeoutException()
}
Executors.newScheduledThreadPool(1).schedule(action, after.toMillis, MILLISECONDS)
Future.firstCompletedOf(Seq(f, p.future))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment