执行器运行时间超过超时值

发布于 2024-09-25 11:54:56 字数 740 浏览 8 评论 0原文

这是scala的一段代码。我将超时设置为 100 mills。在 10000 个循环中,有 106 个循环运行超过 100 个工厂而没有抛出异常。最大的工厂甚至有 135 家。发生这种情况有什么原因吗?

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
  }   
}

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
  }   
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

土豪 2024-10-02 11:54:56

首先,如果您在 Windows 上运行,您应该注意计时器分辨率约为 15.6 毫秒。

其次,1M 次迭代的空循环很可能会被编译器删除,更重要的是,不会被任何超时中断。

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.

挽心 2024-10-02 11:54:56

线程睡眠的工作方式是线程要求操作系统在给定时间后中断它。这就是 result.get 调用中超时的工作原理。现在,您依赖于执行此操作的操作系统线程在超时到期的确切时间运行,当然也可能不是。事实上,您有 10000 个线程可供它中断,但它无法同时完成所有任务。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文