Spring / Spring Retry Interview Questions
How do you implement a custom RetryPolicy in Spring Retry?
You can implement a custom RetryPolicy by implementing the RetryPolicy interface, which gives you full control over whether a retry should be allowed based on any criteria — not just exception type or count. Custom policies are useful when retry decisions depend on application-specific state, such as response content, quota availability, or external configuration.
RetryPolicy interface contract:
public interface RetryPolicy {
boolean canRetry(RetryContext context);
RetryContext open(RetryContext parent);
void close(RetryContext context);
void registerThrowable(RetryContext context, Throwable throwable);
}Custom policy example — retry on specific error codes in the exception message:
public class ErrorCodeRetryPolicy implements RetryPolicy {
private final int maxAttempts;
public ErrorCodeRetryPolicy(int maxAttempts) {
this.maxAttempts = maxAttempts;
}
@Override
public boolean canRetry(RetryContext context) {
Throwable last = context.getLastThrowable();
if (last == null) return true; // first attempt
boolean isRetryableCode = last.getMessage() != null
&& last.getMessage().contains("RETRY_CODE");
return isRetryableCode && context.getRetryCount() < maxAttempts;
}
@Override
public RetryContext open(RetryContext parent) {
return new SimpleRetryContext(parent);
}
@Override
public void close(RetryContext context) {}
@Override
public void registerThrowable(RetryContext context, Throwable throwable) {
((SimpleRetryContext) context).registerThrowable(throwable);
}
}Register it on a RetryTemplate with template.setRetryPolicy(new ErrorCodeRetryPolicy(4)).
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
