Last active
August 29, 2015 14:13
-
-
Save tohenryliu/1b8e498f558122e418a5 to your computer and use it in GitHub Desktop.
TimedFuture
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 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