设置中断位不会使Future.get()抛出TimeoutException

时间:2013-03-04 18:53:32

标签: java timeout interrupt future timeoutexception

为什么不在Callable中设置中断位会导致表示Callable的Future在调用Future.get()时抛出TimeoutException?

public class ExecutorServiceTest extends MockitoTestCase {
  private static CountDownLatch latch1 = new CountDownLatch(1);

  class TaskChecksForInterruptedExcAndDoesSetInterruptedBit implements Callable<String> {
    @Override
    public String call() {
      latch1.countDown();
      while (!Thread.currentThread().isInterrupted()) {
      }
      Thread.currentThread().interrupt();
      return "blah";
    }
  }

  void testInterrupt() throws Exception {
    ExecutorService pool = Executors.newFixedThreadPool(numThreads);
    Future<String> future = pool.submit(new TaskChecksForInterruptedExcAndDoesSetInterruptedBit());
    latch1.await(); // Don't interrupt the Callable until it actually starts processing
    pool.shutdownNow();
    try {
      future.get(100, TimeUnit.MILLISECONDS);
    } catch (final TimeoutException e) {
      // Why doesn't this get called!
      return;
    }
    fail();
  }
}

1 个答案:

答案 0 :(得分:1)

  1. shutdownNow()调用尝试中断所有正在运行的任务。在这种情况下,在繁忙的循环中检测到中断,因此代码继续,Callable返回&#34; blah&#34; (而不是例外)

  2. 根据规范,TimeoutException仅在线程等待完整的超时期限时抛出,但没有结果可用。中断不适合这种情况。

  3. 您对CountDownLatch的使用不正确。你递减了,但我没有看到对latch1.await()

  4. 的调用