Skip to content

Instantly share code, notes, and snippets.

@wenzhihong2003
Forked from crazycode/gist:4970741
Created February 17, 2013 09:20
Show Gist options
  • Save wenzhihong2003/4970753 to your computer and use it in GitHub Desktop.
Save wenzhihong2003/4970753 to your computer and use it in GitHub Desktop.
package util.transaction;
import play.Logger;
import play.db.jpa.JPA;
public class TransactionRetryUtil {
private static final int MAX_TRIED_TIMES = 15;
public static <T> T run(TransactionCallback<T> callback) {
for (int i = 0; i < MAX_TRIED_TIMES; i++) {
try {
if (!JPA.em().getTransaction().isActive()) {
JPA.em().getTransaction().begin();
}
T result = callback.doInTransaction();
if (JPA.em().getTransaction().isActive()) {
JPA.em().getTransaction().commit();
}
return result;
} catch (RuntimeException e) {
if (JPA.em().getTransaction().isActive()) {
JPA.em().getTransaction().rollback();
}
e.printStackTrace();
Logger.info("Found Exception: " + e.getMessage());
Logger.info("wait 1 seconds." + e.toString());
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
//ignore
}
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment