java - Retry logic with CompletableFuture -
i need submit task in async framework i'm working on, need catch exceptions, , retry same task multiple times before "aborting".
the code i'm working is:
int retries = 0; public completablefuture<result> executeactionasync() { // execute action async , future completablefuture<result> f = executemycustomactionhere(); // if future completes exception: f.exceptionally(ex -> { retries++; // increment retry count if (retries < max_retries) return executeactionasync(); // <--- submit 1 more time // abort null value return null; }); // return future return f; }
this doesn't compile because return type of lambda wrong: expects result
, executeactionasync
returns completablefuture<result>
.
how can implement async retry logic?
i solved similar problem using guava-retrying library.
callable<result> callable = new callable<result>() { public result call() throws exception { return executemycustomactionhere(); } }; retryer<boolean> retryer = retryerbuilder.<result>newbuilder() .retryifresult(predicates.<result>isnull()) .retryifexceptionoftype(ioexception.class) .retryifruntimeexception() .withstopstrategy(stopstrategies.stopafterattempt(max_retries)) .build(); completablefuture.supplyasync( () -> { try { retryer.call(callable); } catch (retryexception e) { e.printstacktrace(); } catch (executionexception e) { e.printstacktrace(); } });
Comments
Post a Comment