UniformRandomBackOffPolicy Example (using xml configuration)

In this post under Spring Retry, I will explain with example how to use UniformRandomBackOffPolicy (another implementation of BackOffPolicy interface).

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.

Below is the xml configuration code.

XML code

1  <?xml version="1.0" encoding="UTF-8"?>
2  <beans xmlns="http://www.springframework.org/schema/beans"
3  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
5      <bean id="backOffPolicy" class="org.springframework.retry.backoff.UniformRandomBackOffPolicy">
6          <property name="minBackOffPeriod" value="60000"/>
7          <property name="maxBackOffPeriod" value="600000"/>
8      </bean>
10     <bean id="retryTemplate" class="org.springframework.retry.support.RetryTemplate">
11         <property name="backOffPolicy" ref="backOffPolicy"/>
12     </bean>
14     <bean id="service5" class="Service5"/>
15 </beans>

In the above xml code, at line 5 we have created a bean definition named “backOffPolicy” of class “UniformRandomBackOffPolicy” class.

At line 6 and 7, we set the MinBackOffPeriod and MaxBackOffPeriod, now the policy will choose a random number between the lower and upper bound and wait for that time before retrying the failed operation.

At line 11, we set the property “backOffPolicy” of “RetryTemplate” bean, by referring to the bean “backOffPolicy” created at line 5. By default “RetryTemplate” bean will retry the failed operation 3 times (including the first attempt).

In this way, we use the UniformRandomBackOffPolicy.

Below is the Service and main class for your reference.

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();

Main class

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.retry.support.RetryTemplate;

public class Example13 {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("Example13.xml");
        Service5 service5 = (Service5)context.getBean("service5");
        RetryTemplate retryTemplate =  (RetryTemplate)context.getBean("retryTemplate");

        retryTemplate.execute(retryContext -> { service5.executeWithException(); return null; });


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