Java 为什么scala Future.从不使用倒计时锁存器?
下面是scala 2.12.x中scala.concurrent.Future.never的实现:Java 为什么scala Future.从不使用倒计时锁存器?,java,multithreading,scala,Java,Multithreading,Scala,下面是scala 2.12.x中scala.concurrent.Future.never的实现: final object never extends Future[Nothing] { @throws(classOf[TimeoutException]) @throws(classOf[InterruptedException]) override def ready(atMost: Duration)(implicit permit: CanAwait): this.type = {
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]")
}
...
如您所见,它使用
newcountdownlatch(1).await()阻止当前线程。为什么它比Thread.sleep()
好?看起来它是从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
...
}
好吧,你怎么能永远睡下去呢?一圈<代码>最大长度
?看起来有点笨拙<代码>等待()看起来更干净。此外,它支持纳秒粒度的持续时间