关于Java / Scala中的TimeoutException的困惑

时间:2017-07-13 14:40:25

标签: java scala timeout future

我使用以下玩具代码来测试Scala中的TimeoutException

import java.util.concurrent._

object TestTime {
  def main(args: Array[String]) {
    println("starting....")
    val service = Executors.newSingleThreadExecutor
    try {
      val r = new Runnable() {
        override def run(): Unit = {
          //your task
          val t0 = System.nanoTime: Double
          println(s"1+...+100=${sum(100)}")
          val t1 = System.nanoTime: Double
          println("Elapsed time " + (t1 - t0) / 1e6 + " mill-secs")
        }
      }

      val f = service.submit(r)
      // attempt the task for 0.2 second
      f.get(200, TimeUnit.MILLISECONDS)
    } catch {
      case e: TimeoutException =>
        service.shutdownNow()
        println(s"Timeout: $e")
    } finally {
      service.shutdown()
    }
  }

  //Given that sum() is written by others and I cannot change it.
  def sum(k: Int): BigInt = {
    var total: BigInt = 0
    for (i <- 1 to k) {
      total += i
    }
    total
  }
}

当我运行上述代码时,控制台会显示sum(100)大约29 milliseconds。但是,代码抛出TimeoutException(因为29 < 200,代码不应该TimeoutException)。

enter image description here

当我将f.get(200, TimeUnit.MILLISECONDS)更改为f.get(20, TimeUnit.MILLISECONDS)时。这一次sum需要27 milliseconds,超过了20的阈值。但是,代码会正常显示结果。

enter image description here

0 个答案:

没有答案