Created
February 28, 2015 12:45
-
-
Save nelanka/e0ca3348707900467415 to your computer and use it in GitHub Desktop.
Timeout Future
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 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