views:

70

answers:

1

Here is a code segment of scala. I set timeout as 100 mills. Out of 10000 loops, 106 of them run 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
  }   
}
+6  A: 

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.

Alex Cruise
I changed the for loop to a db call. It doesn't help. When setting 100 millis timeout, the worst case can be more than 1000 millis, 10 times larger than the timeout value.