Skip to content

Instantly share code, notes, and snippets.

@crazycode
Last active August 3, 2018 08:33
Show Gist options
  • Save crazycode/4970741 to your computer and use it in GitHub Desktop.
Save crazycode/4970741 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;
}
}
package util.transaction;
public interface TransactionCallback<T> {
/**
* 事务回调,这个方法的操作是在事务中,如果返回false或抛出异常,都会重试;如果返回true,则成功提交.
* @return
*/
public T doInTransaction();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment