Configuring ExponentialBackOffPolicy for RetryTemplate (using RetryTemplateBuilder)

In this post under Spring Retry, I will show with example how to configure ExponentialBackOffPolicy using RetryTemplateBuilder.

First lets recap what is ExponentialBackOffPolicy is. ExponentialBackOffPolicy increases the backoff period at every retry attempt by a specified number.

ExponentialBackOffPolicy requires three inputs for it to work, which are
1) initialInterval –> the backoff period used at first retry
2) maxInterval –> the max backoff period that is allowed at retry attempt. Spring Retry doesn’t wait more than maxInterval between retry attempts.
3) multiplier –> the value by which backoff period has to incremented at every retry attempt.

We will use the below service class for our example

Service Class

import java.util.Date;

public class Service5 {
    private int i = 0;

    public void executeWithException() {
        i = i + 1;
        System.out.println("Executing method 'executeWithException' : " + i + " at " + new Date());
        throw new NullPointerException();

The Service class has only one method “executeWithException” that will throw NullPointerException whenever it is called.

Below is the xml configuration for your reference

XML file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    <bean id="service5" class="Service5"/>

Below is the main class where we configure ExponentialBackOffPolicy with RetryTemplateBuilder

Main class

1  import org.springframework.context.ApplicationContext;
2  import;
3  import;
5  public class Example22 {
6      public static void main(String[] args) {
7          ApplicationContext context = new ClassPathXmlApplicationContext("Example22.xml");
8          Service5 service5 = (Service5) context.getBean("service5");
9          RetryTemplate retryTemplate = RetryTemplate.builder().exponentialBackoff(100, 1200, 300000).build();
11         retryTemplate.execute(retryContext -> { service5.executeWithException(); return null; });
12     }
13 }

As shown in the above code, at line 9 we create an instance of “RetryTemplate” class using “RetryTemplateBuilder” class.

First we create an instance of “RetryTemplateBuilder” by using its static method “builder”, then we configure “ExponentialBackOffPolicy” by calling “exponentialBackoff” on the builder instance using
method chaining and then finally we call “build”. The “build” method will finally create an instance of RetryTemplate instance with “ExponentialBackOffPolicy” configured.

As per configuration the Spring Retry will wait for 100 ms during first retry attempt. Then for every subsequent retry, the back off period is increased by using the multiplier (ie., 1200). The backoff period will be incremented at every backoff till it goes beyond the 300000 ms.


Press like button if you like the post. Also share your opinion regarding posts through comments. Also mention what other framework you want me to cover through comments.

Leave a Reply