I am new to java functional programming and looking if there is any fancy java 8 feature that I can use for retry logic without much changes to the existing methods in the class:
public class MyClass{
public Pair<Integer, Integer> funA(int paramA, String paramB, int paramC);
public Pair<Integer, String> funB(int paramA);
}
Is it possible to write a wrapper around this class for a generic retry logic that can take any function of this class as input and retry based on the pair key like:
public static T RetryWrapper(Function func)
while(retryCounter < maxRetries){
Pair< Integer, T > result = func.get();
if(result.getKey() > 0)
return result.getValue();
retryCounter ;
}
Any code examples on how to implement and use this would be very helpful.
CodePudding user response:
Maybe you can pass the parametres a List instead of (int i1,int i2 ...) . So your code will look like
public Pair<Integer, Integer> funA(List<Integer> params);
public Pair<Integer, String> funB(List<Integer> params );
public static T RetryWrapper(Function<List<Integer> , Pair<...> > func)
CodePudding user response:
public static T retryWrapper(Supplier<T> func)
while(retryCounter < maxRetries){
Pair< Integer, T > result = func.get();
if(result.getKey() > 0)
return result.getValue();
retryCounter ;
}
and call it as
retryWrapper(() -> funA(1, "2", 3))
retryWrapper(() -> funB(1))