Software Development

More Elegant way to Retry Operations in Java using Spring

This post talks about a better way to retry failed operations in Java using classes in Spring.

Requirements

Stuff used in this post.

  • Spring Core 4.2.1.RELEASE

Retry Codes in Vanilla Java

Off the top of our head, how would we code something that does the following?

  • retries a failed operation n  times
  • each retry, the amount of time to wait before next try increases
  • stops retrying an operation after n  times

[wp_ad_camp_5]

Here’s mine:

Output:

That’s ugly!

Let’s try a better way at doing this.

Back Off

[wp_ad_camp_4]

Spring Core has these related interfaces and classes:

They allow us to create the wait-and-retry functionality in a more elegant way.

Using FixedBackOff

These are sample codes for FixedBackOff.

[wp_ad_camp_3]

Output:

Using ExponentialBackOff

These are codes for ExponentialBackOff.

[wp_ad_camp_2]

Output:

[wp_ad_camp_1]

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like