我有一个Java方法,可以连接到一个Web服务。有时这个方法连接时间太长。如果它的连接时间超过5秒钟,我想要重启当前程序并尝试3次连接。如果所有连接都失败,则完全终止程序。
到目前为止,我已经编写了以下内容:
到目前为止,我已经编写了以下内容:
private ConnectionInterface connectWithTimeout() throws MalformedURLException, Exception {
ExecutorService executor = Executors.newCachedThreadPool();
Callable<Object> task = new Callable<Object>() {
public Object call() throws InterruptedException, MalformedURLException, Exception {
return connectWithNoTimeout(); //This is the method that takes to long. If this method takes more than 5 seconds, I want to cancel and retry for 3 more times. Then abort completely.
}
};
Future<Object> future = executor.submit(task);
try {
Object result = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
System.out.println( "Timeout Occured");
} catch (InterruptedException e) {
System.out.println( " "InterruptedException Occured");
} catch (ExecutionException e) {
System.out.println( ""ExecutionException Occured");
} finally {
future.cancel(true); // here the method gets canceled. How do I retry it?
}
System.out.println( "Connected !!");
return connectWithNoTimeout();
}
private ConnectionInterface connectWithNoTimeout() throws MalformedURLException, Exception {}
connectWithNoTimeout
方法应该在 5 秒超时后运行。现在你只需要再重复两次就可以了吗? - Amongalen