这看起来很不错,但我会从重试中拆分正在运行的任务.也使用泛型,不要只是抛出Object.
使用Java 8 lambda并返回方法:
public static Optional doWithRetry(final Supplier t) {
for (int retry = 0; retry <= StaticData.NETWORK_RETRY; ++retry) {
try {
Thread.sleep(retry * StaticData.NETWORK_CALL_WAIT);
return Optional.of(t.get());
} catch (InterruptedException | UnknownHostException e) {
LOGGER.log(Level.SEVERE, "Call failed.", e);
return Optional.empty();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Call failed. Retry.", e);
}
}
LOGGER.log(Level.SEVERE, "Call failed. Retries exceeded.");
return Optional.empty();
}
另外,使用真正的记录器,而不是printStackTrace ……
用法:
final String data = doWithRetry(() -> {
//do stuff
});
如果你的lambda需要抛出异常,你需要定义自己的@FunctionalInterface:
@FunctionalInterface
interface StuffDoer {
T doStuff() throws Exception;
}
并且在方法签名中使用它,您将需要处理通用异常.
Java 8之前的用法:
final String data = doWithRetry(new StuffDoer() {
@Override
public T get() throws Exception {
return null;
}
});