Skip to content

Instantly share code, notes, and snippets.

@pwpearson
Forked from arschles/scalaFutureTimeout.scala
Created April 14, 2016 22:02
Show Gist options
  • Save pwpearson/fd6c07e23f44857014acaa94b11746c5 to your computer and use it in GitHub Desktop.
Save pwpearson/fd6c07e23f44857014acaa94b11746c5 to your computer and use it in GitHub Desktop.
how to time out a scala future
val realFuture = Future(doRealStuff())
//timeoutFuture does a spin wait by sleeping on the thread on which it runs, so make sure the ExecutionContext
//on which it runs is multi-threaded. In an akka based environment, use a scheduler to fulfill a promise with a failure
//when the timeout duration is complete, and avoid the spin wait
val timeoutFuture = Future {
Thread.sleep(timeoutMilliseconds)
throw new TimeoutException("timeout")
}
Future.firstCompletedOf(realFuture :: timeoutFuture :: Nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment