This post will discuss how to implement retry logic in Java.

1. Simple for-loop with try-catch

A simple solution to implement retry logic in Java is to write your code inside a for loop that executes the specified number of times (the maximum retry value).

The following program demonstrates this. Note that the code is enclosed within a try-catch and if an exception happens inside the try block, the control goes to the catch block. After handling the exception, the system runs the code again after 1 second. After all retries are exhausted and the last re-try fails, the system throws an exception.

Download  Run Code

Output (will vary):

Random number is.. 0
/ by zero
Random number is.. 0
/ by zero
Random number is.. 1

2. Using Interface

We can easily tweak the above logic to isolate the task logic with the retry logic using an interface. The following code demonstrates this.

Download  Run Code

Output (will vary):

Random number is.. 0
/ by zero
Random number is.. 0
/ by zero
Random number is.. 0
/ by zero
Random number is.. 1

3. Third-party libraries

If your project is up for using third-party libraries, we recommend using the following libraries that has strong support for retry logic in Java.

1. Failsafe

Failsafe is a lightweight, zero-dependency library for handling failures in Java 8+. Failsafe works by wrapping executable logic with one or more resilience policies, which can be combined and composed as needed.

To start, create a retry policy that defines which failures should be handled and when retries should be performed:

 
Then you can execute a Runnable or Supplier with retries:

 
Read more – Failsafe Documentation

2. Guava-retrying

The guava-retrying module provides a general purpose method for retrying arbitrary Java code with specific stop, retry, and exception handling capabilities that are enhanced by Guava’s predicate matching.

The minimal sample of some of the functionality would look like:

 
This will retry whenever the result of the Callable is null, if an IOException is thrown, or if any other RuntimeException is thrown from the call() method. It will stop after attempting to retry 3 times and throw a RetryException that contains information about the last failed attempt. If any other Exception pops out of the call() method it’s wrapped and rethrown in an ExecutionException.

Read more – Guava-retrying Documentation

That’s all about implemeting retry logic in Java.