Exceptions, and how best to retry when a connection is reset?

偶尔善良 提交于 2019-12-03 06:56:18

I've been wired to think that swallowing an exception is always bad, but I think here, that's the only way to tell if the connection was indeed reset. I guess you are handling the exception according to your requirements, so that's all the matters.

But I would, however, make it so you don't swallow the last exception. If it fails three times, you'll want to rethrow that exception or fail gracefully somehow.

This is the kind of thing that I'd rather let a bullet-proof connection pool handle for me rather than writing it myself.

AOP and Java annotations should help. I would recommend a read-made mechanism from jcabi-aspects (I'm a developer):

@RetryOnFailure(attempts = 3, delay = 5)
public String load(URL url) {
  return url.openConnection().getContent();
}

You may also try RetryFunc from Cactoos.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!