我正在使用第三方Java库与REST API进行交互。REST API有时可能需要很长时间才能响应,最终导致抛出java.net.ConnectException
。
我想缩短超时时间,但无法修改第三方库。
我想在调用Java方法时应用某种形式的超时控制,这样我就可以确定在什么时候放弃等待。
这与网络超时没有直接关系。我希望能够尝试并执行操作,并且能够在指定的等待时间后放弃。
以下代码绝不是有效的Java代码,但从概念上演示了我想要实现的目标:
try {
Entity entity = new Entity();
entity.methodThatMakesUseOfRestApi();
} catch (<it's been ages now, I don't want to wait any longer>) {
throw TimeoutException();
}
发布于 2011-02-12 21:43:32
我推荐Google Guava库中的TimeLimiter。
发布于 2014-12-21 01:40:28
这可能是目前普通Java应该采用的方式:
public String getResult(final RESTService restService, String url) throws TimeoutException {
// should be a field, not a local variable
ExecutorService threadPool = Executors.newCachedThreadPool();
// Java 8:
Callable<String> callable = () -> restService.getResult(url);
// Java 7:
// Callable<String> callable = new Callable<String>() {
// @Override
// public String call() throws Exception {
// return restService.getResult(url);
// }
// };
Future<String> future = threadPool.submit(callable);
try {
// throws a TimeoutException after 1000 ms
return future.get(1000, TimeUnit.MILLISECONDS);
} catch (ExecutionException e) {
throw new RuntimeException(e.getCause());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new TimeoutException();
}
}
发布于 2011-02-12 21:36:20
没有对任意操作有效的通用超时机制。
虽然...有一个..。使用Thread.stop(Throwable)。它工作,它的线程安全,但当愤怒的暴徒面对你时,你的个人安全处于危险之中。
// realizable
try
{
setTimeout(1s); // 1
... any code // 2
cancelTimeout(); // 3
}
catch(TimeoutException te)
{
// if (3) isn't executed within 1s after (1)
// we'll get this exception
}
https://stackoverflow.com/questions/4978187
复制相似问题