Configuring UniformRandomBackOffPolicy for RetryTemplate (using RetryTemplateBuilder)

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

But before that lets recap what is UniformRandomBackOffPolicy.

UniformRandomBackOffPolicy chooses a random time in ms between user configured MinBackOffPeriod and MaxBackOffPeriod and then before a failed operations is retried, it pauses for that time.

For our example we will use the below Service class

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 above Service class has one method named “executeWithException” that will throw NullPointerException.

Below is the xml code for your reference

XML code

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

In the above xml code, I have a bean definition for Service class.

Next we will see the main code where we configure UniformRandomBackOffPolicy using RetryTemplateBuilder class

Main class

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

In the above java code, at line 9, we create RetryTemplate instance configured with UniformRandomBackOffPolicy by calling the below method

RetryTemplate.builder().uniformRandomBackoff(60000, 600000).build();

As per the code, it creates a RetryTemplate instance with UniformRandomBackOffPolicy configured and the UniformRandomBackOffPolicy will choose a random value between 60000 and 600000 and wait for that time before retrying the failed operation.

In this way we can configure UniformRandomBackOffPolicy using RetryTemplateBuilder class.

Leave a Reply