future java get_为什么Java Future.get(超时)不可靠?

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) {

}

}

}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部