1 17 18 package org.apache.geronimo.timer; 19 20 import javax.transaction.TransactionManager ; 21 import javax.transaction.Status ; 22 23 import org.apache.commons.logging.Log; 24 import org.apache.commons.logging.LogFactory; 25 26 29 public class TransactionalExecutorTask implements ExecutorTask { 30 private static final Log log = LogFactory.getLog(TransactionalExecutorTask.class); 31 32 private final Runnable userTask; 33 private final WorkInfo workInfo; 34 private final ThreadPooledTimer threadPooledTimer; 35 36 private final TransactionManager transactionManager; 37 private final int repeatCount; 38 39 public TransactionalExecutorTask(Runnable userTask, WorkInfo workInfo, ThreadPooledTimer threadPooledTimer, TransactionManager transactionManager, int repeatCount) { 40 this.userTask = userTask; 41 this.workInfo = workInfo; 42 this.threadPooledTimer = threadPooledTimer; 43 this.transactionManager = transactionManager; 44 this.repeatCount = repeatCount; 45 } 46 47 public void run() { 48 try { 49 boolean succeeded = false; 51 for (int tries = 0; !succeeded && tries < repeatCount; tries++) { 52 try { 53 if (!beginWork()) { 54 break; 55 } 56 57 work(); 58 } finally { 59 succeeded = completeWork(); 60 } 61 } 62 63 if (workInfo.isOneTime()) { 65 threadPooledTimer.removeWorkInfo(workInfo); 66 } 67 68 if (!succeeded) { 70 log.warn("Failed to execute work successfully"); 71 } 72 } catch (RuntimeException e) { 73 log.warn("RuntimeException occured while running user task", e); 74 throw e; 75 } catch (Error e) { 76 log.warn("Error occured while running user task", e); 77 throw e; 78 } 79 } 80 81 private boolean beginWork() { 82 try { 83 transactionManager.begin(); 84 } catch (Exception e) { 85 log.warn("Exception occured while starting container transaction", e); 86 return false; 87 } 88 return true; 89 } 90 91 private void work() { 92 try { 93 userTask.run(); 94 } catch (Exception e) { 95 log.warn("Exception occured while running user task", e); 96 } 97 } 98 99 private boolean completeWork() { 100 try { 101 if (transactionManager.getStatus() == Status.STATUS_ACTIVE) { 102 try { 104 threadPooledTimer.workPerformed(workInfo); 105 } catch (PersistenceException e) { 106 log.warn("Exception occured while updating timer persistent state", e); 107 } 108 109 transactionManager.commit(); 111 112 return true; 114 } else { 115 transactionManager.rollback(); 117 } 118 } catch (Exception e) { 119 log.warn("Exception occured while completing container transaction", e); 120 } 121 return false; 123 } 124 125 } 126 | Popular Tags |