net.e6tech.elements.common.resources.Retry Maven / Gradle / Ivy
/*
* Copyright 2015-2019 Futeh Kao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.e6tech.elements.common.resources;
/**
* Created by futeh.
*/
@SuppressWarnings("squid:S00112")
public abstract class Retry {
private int limit = 3;
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public abstract boolean shouldRetry(Throwable th);
public R retry(Retryable call) throws Throwable {
return privateRetry(null, call);
}
public R retry(Throwable exception, Retryable call) throws Throwable {
return privateRetry(exception, call);
}
protected R privateRetry(Throwable exception, Retryable call) throws Throwable {
R ret = null;
Throwable error = exception;
boolean success = false;
int count = 0;
while ((error == null || shouldRetry(error)) && count < limit) {
if (error != null) {
count ++;
}
try {
ret = call.call();
success = true;
break;
} catch (Throwable th) {
error = th;
}
}
if (!success && error != null)
throw error;
return ret;
}
@FunctionalInterface
public interface Retryable {
R call() throws Throwable;
}
}