Skip to content

Instantly share code, notes, and snippets.

@tohenryliu
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tohenryliu/1b8e498f558122e418a5 to your computer and use it in GitHub Desktop.
Save tohenryliu/1b8e498f558122e418a5 to your computer and use it in GitHub Desktop.
TimedFuture
import scala.concurrent._
import scala.concurrent.duration._
object TimedFuture {
def apply[T](body: ⇒ T)(timeout: Duration = 10.seconds)(implicit executor: ExecutionContext): Future[T] = {
val start = System.currentTimeMillis()
Future {
val now = System.currentTimeMillis()
if (now - start > timeout.toMillis) throw new Exception(s"timed out after $timeout")
body
}
}
def example = {
import scala.concurrent.ExecutionContext.Implicits.global
val f = TimedFuture{
Thread.sleep(11000)
1
}() // times out
val f2 = TimedFuture{
Thread.sleep(11000)
1
}(1.second) // times out
}
def test = {
import scala.concurrent.ExecutionContext.Implicits.global
val blockers = (1 to 10).foreach(n=> Future(Thread.sleep(2000)))
val testFuture = TimedFuture{
println("this should not output") // to prove the work is not executed
1
}(1.second)
Await.result(testFuture, Duration.Inf)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment