Skip to content

Instantly share code, notes, and snippets.

@roothybrid7
Created September 4, 2011 03:29
Show Gist options
  • Save roothybrid7/1192196 to your computer and use it in GitHub Desktop.
Save roothybrid7/1192196 to your computer and use it in GitHub Desktop.
Slim3 GlobalTransaction Memo
package jp.rh7.utils;
public interface DataHandler {
// Transactionで実行する処理をここに書く
public abstract void execute();
// モデルを取り出す
public abstract Object[] getModels();
}
package jp.rh7.dao;
import org.slim3.datastore.Datastore;
import org.slim3.datastore.GlobalTransaction;
import jp.rh7.utils.DataHandler;
public class PersistWithTx {
private static final int RETRIES = 5;
private static final int MSLEEP = 500;
/**
* Static Class (DO NOT Instantiate!!)
*/
private PersistWithTx() {
throw new AssertionError();
}
public static void save(DataHandler handler) {
RuntimeException error = null;
// 成功するまで繰り返す
for (int i = 0; i < RETRIES; i++) {
GlobalTransaction gtx = Datastore.beginGlobalTransaction();
try {
handler.execute();
gtx.put(handler.getModels());
gtx.commit();
error = null;
} catch (Exception e) {
e.printStackTrace();
try {
// 失敗した場合はしばらく待つ
Thread.sleep(MSLEEP);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
error = new RuntimeException(e);
continue; // リトライ
} finally {
if (gtx.isActive()) {
gtx.rollback();
}
}
if (error == null) return;
}
throw error;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment