-
-
Save wenzhihong2003/4970753 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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