Kill or timeout a Future in Scala 2.10

前端 未结 3 1936
失恋的感觉
失恋的感觉 2021-01-04 20:11

Hi,

I\'m using Scala 2.10 with the new futures library and I\'m trying to write some code to test an infinite loop. I use a scala.concurrent.Future to r

3条回答
  •  难免孤独
    2021-01-04 20:19

    I had a similar problem and wrote the following nonblocking future op:

    class TerminationToken(var isTerminated: Boolean)
    object TerminationToken { def apply() = new TerminationToken(false) }
    
     implicit class FutureOps[T](future: Future[Option[T]]) {
     def terminate(timeout: FiniteDuration, token: TerminationToken): Future[Option[T]] = {
       val timeoutFuture = after[Option[T]](timeout, using = context.system.scheduler) {
         Future[Option[T]] { token.isTerminated = true; None } }
              Future.firstCompletedOf[Option[T]](Seq (future recover { case _ => None }, timeoutFuture))
         }
       }
    

    Then just create a future that returns an option, and use .terminate(timeout, token) on it

提交回复
热议问题