Failsafe Timeout Policy

September 13, 2020 No comments Failsafe Java library Timeout policy

1. Introduction

In this short article, we are going to present how to use the Timeout policy available in the Failsafe library. Timeouts allow you to fail an execution with TimeoutExceededException if it takes too long to complete.

2. Basic use

To start using Timeout first we need to create an instance of this object like in the following code:

Timeout<Object> timeout = Timeout.of(Duration.ofSeconds(10));

then we can use it in Failsafe.with(...) method to handle timeout on specific execution:

Failsafe.with(timeout)
        .run(connection::connect);

3. Event listeners

Timeouts support the standard policy listeners which can notify you when a timeout is exceeded:

timeout.onFailure(e -> log.error("Connection attempt timed out", e.getFailure()));

Or when an execution completes and the timeout is not exceeded:

timeout.onSuccess(e -> log.info("Execution completed on time"));

4. JUnit test

In the following JUnit test we created a Timeout object that should interrupt execution after 10 seconds:

package com.frontbackend.libraries.failsafe;

import static org.mockito.Mockito.when;

import java.net.ConnectException;
import java.time.Duration;
import java.util.Date;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import net.jodah.failsafe.Failsafe;
import net.jodah.failsafe.Timeout;
import net.jodah.failsafe.TimeoutExceededException;

@RunWith(MockitoJUnitRunner.class)
public class TimeoutPolicyTest {

    @Mock
    DatabaseConnection connection = new DatabaseConnection();

    @Test(expected = TimeoutExceededException.class)
    public void testTimeout() throws ConnectException {
        // given
        Timeout<Object> timeout = Timeout.of(Duration.ofSeconds(10));
        timeout.onFailure(e -> log(String.format("Connection attempt timed out%s", e.getFailure())));
        timeout.onSuccess(e -> log("Execution completed on time"));

        // when
        when(connection.connect()).then(invocationOnMock -> {
            Thread.sleep(12000);
            return null;
        });

        Failsafe.with(timeout)
                .run(connection::connect);
    }

    private void log(String log) {
        System.out.printf("%s : %s%n", new Date(), log);
    }
}

The output:

Sun Sep 13 21:27:47 CEST 2020 : Connection attempt timed outnet.jodah.failsafe.TimeoutExceededException

5. Conclusion

In this article, we presented how to use the Timeout policy in the Failsafe library. This is the simplest way to interrupt the execution of any code when if it takes too long to complete.

{{ message }}

{{ 'Comments are closed.' | trans }}