A Groovy way to retry method calls in case of exceptions

In some scenarios, method calls can fail – but would succeed when retrying the call after some seconds have passed.

That is often the case with remote method calls, where the remote application could be temporarily unavaillable.

I needed a simple way to define something like

“call method foo(). In case the method throws an Exception, retry to call it up to 10 times with a delay of 3 seconds”.

I implemented a simple Groovy util class which enabled me to write code as follows:

RetryUtil.retry(10, 3000){
	foo()
}

Here is the sourcecode of the RetryUtil Groovy class:

import org.apache.commons.logging.LogFactory
import org.apache.commons.logging.Log

class RetryUtil {

	private static Log log = LogFactory.getLog(RetryUtil);

	static retry(int times, long sleeptime, Closure c){
		Throwable catchedThrowable = null
		for(int i=0; i<times; i++){
			try {
				return c.call()
			} catch(Throwable t){
				catchedThrowable = t
				log.warn("failed to call closure. ${i+1} of $times runs.")
				Thread.sleep(sleeptime)
			}
		}
		log.error("finally failed to call closure after $times tries.")
		throw catchedThrowable
	}
}
This entry was posted in Groovy and Grails and tagged , . Bookmark the permalink.

One Response to A Groovy way to retry method calls in case of exceptions

  1. Pingback: Grails cette semaine (2011-12) – Traduction de l’article original

Leave a Reply