Created
September 4, 2011 03:29
-
-
Save roothybrid7/1192196 to your computer and use it in GitHub Desktop.
Slim3 GlobalTransaction Memo
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 jp.rh7.utils; | |
public interface DataHandler { | |
// Transactionで実行する処理をここに書く | |
public abstract void execute(); | |
// モデルを取り出す | |
public abstract Object[] getModels(); | |
} |
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 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