1 8 9 package com.sleepycat.collections; 10 11 import com.sleepycat.compat.DbCompat; 12 import com.sleepycat.je.DatabaseException; 13 import com.sleepycat.je.DeadlockException; 14 import com.sleepycat.je.Environment; 15 import com.sleepycat.je.Transaction; 16 import com.sleepycat.je.TransactionConfig; 17 import com.sleepycat.util.ExceptionUnwrapper; 18 19 74 public class TransactionRunner { 75 76 77 public static final int DEFAULT_MAX_RETRIES = 10; 78 79 private CurrentTransaction currentTxn; 80 private int maxRetries; 81 private TransactionConfig config; 82 private boolean allowNestedTxn; 83 84 91 public TransactionRunner(Environment env) { 92 93 this(env, DEFAULT_MAX_RETRIES, null); 94 } 95 96 110 public TransactionRunner(Environment env, 111 int maxRetries, 112 TransactionConfig config) { 113 114 this.currentTxn = CurrentTransaction.getInstance(env); 115 this.maxRetries = maxRetries; 116 this.config = config; 117 } 118 119 123 public int getMaxRetries() { 124 125 return maxRetries; 126 } 127 128 133 public void setMaxRetries(int maxRetries) { 134 135 this.maxRetries = maxRetries; 136 } 137 138 147 public boolean getAllowNestedTransactions() { 148 149 return allowNestedTxn; 150 } 151 152 161 public void setAllowNestedTransactions(boolean allowNestedTxn) { 162 163 if (allowNestedTxn && !DbCompat.NESTED_TRANSACTIONS) { 164 throw new UnsupportedOperationException ( 165 "Nested transactions are not supported."); 166 } 167 this.allowNestedTxn = allowNestedTxn; 168 } 169 170 180 public TransactionConfig getTransactionConfig() { 181 182 return config; 183 } 184 185 195 public void setTransactionConfig(TransactionConfig config) { 196 197 this.config = config; 198 } 199 200 216 public void run(TransactionWorker worker) 217 throws DatabaseException, Exception { 218 219 if (currentTxn != null && 220 (allowNestedTxn || currentTxn.getTransaction() == null)) { 221 222 225 for (int i = 0;; i += 1) { 226 Transaction txn = null; 227 try { 228 txn = currentTxn.beginTransaction(config); 229 worker.doWork(); 230 if (txn != null && txn == currentTxn.getTransaction()) { 231 currentTxn.commitTransaction(); 232 } 233 return; 234 } catch (Throwable e) { 235 e = ExceptionUnwrapper.unwrapAny(e); 236 if (txn != null && txn == currentTxn.getTransaction()) { 237 try { 238 currentTxn.abortTransaction(); 239 } catch (Throwable e2) { 240 241 246 if (DbCompat.TRANSACTION_RUNNER_PRINT_STACK_TRACES) { 247 e2.printStackTrace(); 248 } 249 250 i = maxRetries + 1; 251 } 252 } 253 if (i >= maxRetries || !(e instanceof DeadlockException)) { 254 if (e instanceof Exception ) { 255 throw (Exception ) e; 256 } else { 257 throw (Error ) e; 258 } 259 } 260 } 261 } 262 } else { 263 264 267 try { 268 worker.doWork(); 269 } catch (Exception e) { 270 throw ExceptionUnwrapper.unwrap(e); 271 } 272 } 273 } 274 } 275 | Popular Tags |