为什么 Java Future.get(timeout) 不可靠?
2022-09-01 14:31:45
Future.get(timeout) 在给定的超时后不会可靠地抛出 TimeoutException。这是正常行为还是我可以做些什么来使其更可靠?此测试在我的计算机上失败。但是,如果我睡了3000而不是2000,它就会过去。
public class FutureTimeoutTest {
@Test
public void test() throws
ExecutionException,
InterruptedException {
ExecutorService exec = Executors.newSingleThreadExecutor();
final Callable call = new Callable() {
@Override
public Object call() throws Exception {
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
return 0;
}
};
final Future future = exec.submit(call);
try {
future.get(1000, TimeUnit.MILLISECONDS);
fail("expected TimeoutException");
} catch (TimeoutException ignore) {
}
}
}