【问题标题】:Sequencing `Future`s with timeout用超时对“未来”进行排序
【发布时间】:2014-03-25 20:26:17
【问题描述】:

我使用了Scala Futures - built in timeout? 介绍的TimeoutScheduler。

但是,如果没有TimeoutScheduler,现在我的程序不会像以前那样终止。

我有两个Futures:res1 和 res2。两者都有 15 秒的超时。最后,我对Futures 进行了排序,以便在onComplete 回调中正确关闭HTTP 执行器。如果不使用withTimeout,程序会在http.shutdown 之后立即终止。但是使用withTimeout 不会。为什么?肯定还有未来……

import java.net.URI
import scala.util.{ Try, Failure, Success }
import dispatch._
import org.json4s._
import org.json4s.native.JsonMethods._
import com.typesafe.scalalogging.slf4j.Logging

object Main extends App with Logging {
  import scala.concurrent.ExecutionContext.Implicits.global

  val http   = Http
  val github = host("api.github.com").secure 

  import timeout._
  import scala.concurrent.duration._
  import scala.language.postfixOps
  import scala.collection.JavaConverters._

  val req: dispatch.Req =  github / "users" / "defunkt"
  val res1 = http(req > dispatch.as.Response(_.getHeaders().get("Server").asScala)) withTimeout (15 seconds) recover { case x => 
    logger.debug("Error1: " + x.toString) 
    Nil
  }
  val res2 = http(req > dispatch.as.Response(_.getHeaders().get("Vary").asScala)) withTimeout (15 seconds) recover { case x => 
    logger.debug("Error2: " + x.toString) 
    Nil
  }

  Future.sequence(res1 :: res2 :: Nil) onComplete { case _ => 
    http.shutdown()               // without using `withTimeout` the program terminated after `http.shutdow`
    TimeoutScheduler.timer.stop() // thanks to @cmbaxter
  }
}

object timeout {
  import java.util.concurrent.TimeUnit
  import scala.concurrent.Promise
  import scala.concurrent.duration.Duration
  import org.jboss.netty.util.Timeout
  import org.jboss.netty.util.TimerTask
  import org.jboss.netty.util.HashedWheelTimer
  import org.jboss.netty.handler.timeout.TimeoutException

   // cf. https://stackoverflow.com/questions/16304471/scala-futures-built-in-timeout
  object TimeoutScheduler {
    val timer = new HashedWheelTimer(10, TimeUnit.MILLISECONDS)
    def scheduleTimeout(promise: Promise[_], after: Duration) = {
      timer.newTimeout(new TimerTask{
        def run(timeout: Timeout){              
          promise.failure(new TimeoutException("Operation timed out after " + after.toMillis + " millis"))        
        }
      }, after.toNanos, TimeUnit.NANOSECONDS)
    }
  }
  implicit class FutureWithTimeout[T](f: Future[T]) {
    import scala.concurrent.ExecutionContext

    def withTimeout(after: Duration)(implicit ec: ExecutionContext) = {
      val prom = Promise[T]()
      val timeout = TimeoutScheduler.scheduleTimeout(prom, after)
      val combinedFut = Future.firstCompletedOf(List(f, prom.future))
      f onComplete { case result => timeout.cancel() }
      combinedFut
    }
  } 
}

欢迎提出任何建议,Best,/nm

【问题讨论】:

    标签: scala future scala-dispatch


    【解决方案1】:

    如果您完全按照描述使用我的代码,那么我的猜测是位于 TimeoutScheduler 对象下的 Netty HashedWheelTimer 没有被终止。您可以尝试在调用http.shutdown 之后显式调用stop,如下所示:

    TimeoutScheduler.timer.stop
    

    现在,如果您希望 Netty HashedWheelTimer 使用守护线程,那么您可以使用其中一个接受 ThreadFactory 的构造函数(我在 3.6.6-Final 中看到它们),然后使用将守护进程标志设置为 true 的自定义 ThreadFactory。

    【讨论】:

    • 好吧,我只是稍微修改了你的代码。你认为这是问题吗?整个代码在我最初的帖子中。你的在最后。或者HashedWheelTimer 不是守护进程(由 Viktor Klang 建议)?
    • 是的,HashedWheelTimer 线程是非守护进程,因此如果您想将该类用作高效的计时器机制,则必须明确停止它。不过,计时器类可能有不同的选项,因此您也可以研究一下。我使用HashedWheelTimer 只是为了示例的完整性。如果您不喜欢明确关闭它,请不要觉得您必须使用它。
    • 感谢您的回复。我可以明确地关闭它。只是好奇我是否真的需要。感谢您的澄清。最后但并非最不重要的一点是,出于教学目的,您是否知道我可以使用的一种恶魔替代方案,只是为了更好地理解?最佳,/nm
    • 看来我说得太早了。似乎 Netty HashedWheelTimer 支持一个接受 ThreadFactory 的构造函数,该 ThreadFactory 用于生成表示计时器的线程。如果您使用该构造函数,您应该能够传入一个自定义的ThreadFactory,它将Thread 上的守护进程标志设置为返回true。
    • 感谢您的帮助和调查!你说的对!我改为new HashedWheelTimer(new DefaultDaemonicThreadFactory, 10, TimeUnit.MILLISECONDS),而DefaultDaemonicThreadFactory 是Executors#DefaultThreadFactory 的原始副本,但使用t.setDaemon(true)。有用! TimeoutScheduler.timer.stop(),在这种情况下,是不必要的。
    猜你喜欢
    • 2021-07-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    相关资源
    最近更新 更多