2017-07-01 7 views
0

はScalaの2.12.xからscala.concurrent.Future.neverの実装です:scala Future.neverがCountDownLatchを使用する理由は何ですか?ここ

final object never extends Future[Nothing] { 

@throws(classOf[TimeoutException]) 
@throws(classOf[InterruptedException]) 
override def ready(atMost: Duration)(implicit permit: CanAwait): this.type = { 
    atMost match { 
    case e if e eq Duration.Undefined => throw new IllegalArgumentException("cannot wait for Undefined period") 
    case Duration.Inf  => new CountDownLatch(1).await() 
    case Duration.MinusInf => // Drop out 
    case f: FiniteDuration => 
     if (f > Duration.Zero) new CountDownLatch(1).await(f.toNanos, TimeUnit.NANOSECONDS) 
    } 
    throw new TimeoutException(s"Future timed out after [$atMost]") 
} 
... 

あなたはそれが現在のスレッドをブロックするnew CountDownLatch(1).await()を使用して見ることができるように。なぜそれはThread.sleep()よりも優れていますか?

答えて

-1

Awaitable.scalaから実装しているようです。あなたの右のブロックは良くありませんが、それは文書化されています。

/** 
* An object that may eventually be completed with a result value of type `T` which may be 
* awaited using blocking methods. 
* 
* The [[Await]] object provides methods that allow accessing the result of an `Awaitable` 
* by blocking the current thread until the `Awaitable` has been completed or a timeout has 
* occurred. 
*/ 
trait Awaitable[+T] { 

    /** 
    * Await the "completed" state of this `Awaitable`. 
    * 
    * '''''This method should not be called directly; use [[Await.ready]] instead.''''' 
    * 
    * @param atMost 
    *   maximum wait time, which may be negative (no waiting is done), 
    *   [[scala.concurrent.duration.Duration.Inf Duration.Inf]] for unbounded waiting, or a finite positive 
    *   duration 
    * @return this `Awaitable` 
    * @throws InterruptedException  if the current thread is interrupted while waiting 
    * @throws TimeoutException   if after waiting for the specified time this `Awaitable` is still not ready 
    * @throws IllegalArgumentException if `atMost` is [[scala.concurrent.duration.Duration.Undefined Duration.Undefined]] 
    */ 
    @throws(classOf[TimeoutException]) 
    @throws(classOf[InterruptedException]) 
    def ready(atMost: Duration)(implicit permit: CanAwait): this.type 

    ... 
} 
0

どうしてよろしいですか?Thread.sleepあなたは永遠にどのようにしますか?ループ? MAX_LONG?見た目はちょっとぎこちない。 await()はきれいだと思われます。また、ナノ秒単位の持続時間をサポートします。

関連する問題