Repeatable code

How often do you want to repeat a chunk of code? A request for a resource times out due to a temporary network issue. How do you handle this?

Last week I was in the creative corner and after having checked out the RetryTemplate from Spring Batch I  figured I wanted something more stylish and configurable – in the least possible number of lines.

After adopting JMock into our unit testing toolbox, I’ve become increasingly fond of the syntax proposed by that framework (among others). So I decided a similar syntax for configuring my RetryManager would be fun to try implementing.

RetryManager.instance().numberOfTimes(5).onExceptions(IOException.class).retry(new Retryable() {

    public void execute() {

        // Here goes your retryable code.
    }
});

As you see from the example above, the amount of space occupied by the configuration and execution code is not overwhelming at all.

Currently the implementation is at a prototype stage, but in a few days time we hope to have implemented more configuration options such as delays and the option to specify fail/retry strategies instead of just a list of exceptions. We  also want to make the RetryManager available through an open source library, together with other boiler plate code – we are working on figuring out the last details on that.

Feel free to give your throughs on the solution presented above and if you have used another solution to a similar problem.

About Jaran Nilsen

I've been working as a lead developer at Integrasco AS since it's startup in 2004. My interests in software development are ranging from the lowest bit to design patterns and development methods. On a daily basis my main area of responsibility is data mining technology as well as a bit of team management. In addition to my work at Integrasco AS, I am also running an open source project called iTunes Agent over on Sourceforge, which provides non-iPod owners with a way to transfer music from iTunes to their media player.