Spring / Spring Retry Interview Questions
What is a RetryContext and what information does it carry?
RetryContext is an object created by Spring Retry at the start of each retry sequence and passed through every retry attempt. It acts as a stateful record of the current retry operation, storing information that policies, listeners, and recovery callbacks can inspect or modify.
Key information available in RetryContext:
- Retry count:
context.getRetryCount()returns the number of attempts completed so far (0 on the first try). - Last exception:
context.getLastThrowable()returns the exception that caused the most recent failure. - Exhausted flag:
context.isExhaustedOnly()indicates that retries were exhausted by external signal rather than policy. - Attribute store:
context.setAttribute(key, value)/context.getAttribute(key)let you attach custom data for use across attempts or in listeners.
Accessing RetryContext in a recovery callback:
retryTemplate.execute(context -> { log.info("Attempt: " + context.getRetryCount()); return callService(); }, context -> { Throwable ex = context.getLastThrowable(); log.error("Giving up after " + context.getRetryCount() + " attempts", ex); return "fallback"; });
Custom retry listeners also receive the RetryContext on open, close, and onError callbacks, making it the central coordination object for cross-cutting retry concerns.
More Related questions...