Skip to content

Instantly share code, notes, and snippets.

@bassemZohdy
Created September 3, 2015 19:52
Show Gist options
  • Save bassemZohdy/60d1109c171aa59f94ec to your computer and use it in GitHub Desktop.
Save bassemZohdy/60d1109c171aa59f94ec to your computer and use it in GitHub Desktop.
import java.util.function.Supplier;
public class BlockingSupplierWithRetry<T> implements Supplier<T> {
private final Supplier<T> supplier;
private final int tries;
private final T defaultValue;
private final long sleep;
private final Class<? extends Throwable> throwableClass;
private BlockingSupplierWithRetry(Supplier<T> supplier, int tries,
T defaultValue, long sleep,
Class<? extends Throwable> throwableClass) {
this.supplier = supplier;
this.tries = tries;
this.defaultValue = defaultValue;
this.sleep = sleep;
this.throwableClass = throwableClass;
}
public static <T> BlockingSupplierWithRetry<T> of(Supplier<T> supplier,
int tries, T defaultValue, long sleep,
Class<? extends Throwable> throwableClass) {
return new BlockingSupplierWithRetry<T>(supplier, tries, defaultValue,
sleep, throwableClass);
}
@Override
public T get() {
try {
return supplier.get();
} catch (Throwable t) {
if (throwableClass.isInstance(t)) {
if (tries <= 0)
return defaultValue;
System.out.println(Thread.currentThread().getName()
+ " >> Exception " + t + " try with tries "
+ (tries - 1));
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return BlockingSupplierWithRetry.of(supplier, tries - 1,
defaultValue, sleep, throwableClass).get();
}
throw t;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment