java 设置超时_如何在Java方法中设置超时,并定期重试该方法

我java了一个java方法,它连接到web服务。

我想举例来说,它需要超过5秒,然后停止当前的程序和重新启动3次以上。如果所有时间都失败,则完全中止。

到目前为止,我写了以下内容:

private ConnectionInterface connectWithTimeout() throws MalformedURLException, Exception {

ExecutorService executor = Executors.newCachedThreadPool();

Callable task = new Callable() {

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值