Updated 2019-08-08: Using new version with lambda expressions.
This is already the second Java post within a few days. This time, I want to demonstrate, how to retry some specific code when an Exception or an Error is thrown. This might be helpful when dealing with distributed systems and a first call didn’t bring success. My first attempts in researching a solution for this were not very satisfying. Most times you only could retry the whole method or just use a simple loop. But I wanted something more granular and more extensible without copying the same loops over and over again. The closest solution I found was the “enterprisy” Stackoverflow answer by ach - which lost against the simple loop as the correct answer ;-). In this post, I want to present a slightly enhanced version of the retry functionality with Java 8 compatibility.
For Throwables (Exceptions and Errors). You shouldn’t use this in “normal” application code, only in tests.
For Exceptions only. Use this in your “normal” application code.
The implementation could be further enhanced, e.g. it should be possible to only retry on some specific Throwables (blacklist) or not retry on specific Throwables (whitelist).
» Source Code
The latest version of the code can be found in the git repository.