开发者

Executors run longer than timeout value

Here is a code segment of scala. I set timeout as 100 mills. Out of 10000 loops, 106 of them ru开发者_开发问答n more than 100 mills without throwing exceptions. The largest one is even 135 mills. Any reason why this is happening?

for (j <- 0 to 10000) {
  total += 1
  val executor = Executors.newSingleThreadExecutor
  val result = executor.submit[Int](new Callable[Int] {
      def call = try {
        Thread.sleep(95)
        for (i <- 0 to 1000000) {}
        4   
      } catch {
        case e: Exception => exception1 += 1
        5   
      }   
  })  

  try {
    val t1 = Calendar.getInstance.getTimeInMillis
    result.get(100, TimeUnit.MILLISECONDS)
    val t2 = Calendar.getInstance.getTimeInMillis
    println("timediff = " + (t2 - t1).toString)
  } catch {
    case e: Exception => exception2 += 1
  }   
}


Firstly, if you're running on Windows you should be aware that the timer resolution is around 15.6 milliseconds.

Secondly, your empty loop of 1M iterations is quite likely to be removed by a compiler, and more importantly, can't be interrupted by any timeout.


The way a thread sleep works is that a thread asks the o/s to interrupt it after the given time. That's how the timeout works in the result.get call. Now you're relying on the OS thread that does this to be running at the exact time when your timeout has expired, which of course it may not be. Then there is the fact you have 10000 threads for it to interrupt which it can't do all at the exact same time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜