A Simple Spring Retry Example

While looking for an alternative for the ugly Thread.sleep() in a retry loop:

try {
    Thread.sleep(250);
} catch (InterruptedException e) {
    Thread.interrupted();
}

I stumbled over the RetryTemplate from the lesser known Spring project spring-projects/spring-retry.

Let's create a RetryTemplate with an ExponentialBackOffPolicy:

private RetryTemplate createRestTemplate() {
    RetryTemplate retryTemplate = new RetryTemplate();
    // wait approximately one minute
    retryTemplate.setRetryPolicy(new SimpleRetryPolicy(8, singletonMap(IllegalStateException.class, true)));
    retryTemplate.setBackOffPolicy(new ExponentialBackOffPolicy());
    return retryTemplate;
}

The actual retry loop (which waits until an entity has been marked as deleted) looks like this:

createRestTemplate().execute((RetryCallback<Void, IllegalStateException>) context -> {
    if (findEntity(id).isPresent()) {
        LOG.debug("Entity '{}' still available.", id);
        throw new IllegalStateException();
    }
    return null;
});
}

Way better than the Thread.sleep() where we started...