Coverage Report - org.kuali.rice.ken.service.impl.ConcurrentJob
 
Classes in this File Line Coverage Branch Coverage Complexity
ConcurrentJob
0%
0/63
0%
0/20
2.667
ConcurrentJob$1
0%
0/2
N/A
2.667
ConcurrentJob$2
0%
0/12
0%
0/2
2.667
ConcurrentJob$2$1
0%
0/2
N/A
2.667
ConcurrentJob$3
0%
0/4
N/A
2.667
 
 1  
 /*
 2  
  * Copyright 2007 The Kuali Foundation
 3  
  * 
 4  
  * Licensed under the Educational Community License, Version 2.0 (the "License");
 5  
  * you may not use this file except in compliance with the License.
 6  
  * You may obtain a copy of the License at
 7  
  * 
 8  
  * http://www.opensource.org/licenses/ecl2.php
 9  
  * 
 10  
  * Unless required by applicable law or agreed to in writing, software
 11  
  * distributed under the License is distributed on an "AS IS" BASIS,
 12  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  
  * See the License for the specific language governing permissions and
 14  
  * limitations under the License.
 15  
  */
 16  
 package org.kuali.rice.ken.service.impl;
 17  
 
 18  
 import java.sql.SQLException;
 19  
 import java.sql.Timestamp;
 20  
 import java.util.ArrayList;
 21  
 import java.util.Collection;
 22  
 import java.util.Iterator;
 23  
 import java.util.List;
 24  
 import java.util.concurrent.Callable;
 25  
 import java.util.concurrent.ExecutorService;
 26  
 import java.util.concurrent.Future;
 27  
 
 28  
 import org.apache.commons.lang.StringUtils;
 29  
 import org.apache.log4j.Logger;
 30  
 import org.apache.ojb.broker.OptimisticLockException;
 31  
 import org.kuali.rice.ken.service.ProcessingResult;
 32  
 import org.kuali.rice.ken.util.Util;
 33  
 import org.springframework.dao.DataAccessException;
 34  
 import org.springframework.transaction.PlatformTransactionManager;
 35  
 import org.springframework.transaction.TransactionException;
 36  
 import org.springframework.transaction.TransactionStatus;
 37  
 import org.springframework.transaction.UnexpectedRollbackException;
 38  
 import org.springframework.transaction.support.TransactionCallback;
 39  
 import org.springframework.transaction.support.TransactionTemplate;
 40  
 
 41  
 /**
 42  
  * Base class for jobs that must obtain a set of work items atomically
 43  
  * @author Kuali Rice Team (rice.collab@kuali.org)
 44  
  */
 45  
 public abstract class ConcurrentJob<T> {
 46  
     /**
 47  
      * Oracle's "ORA-00054: resource busy and acquire with NOWAIT specified"
 48  
      */
 49  
     private static final int ORACLE_00054 = 54;
 50  
     /**
 51  
      * Oracle's "ORA-00060 deadlock detected while waiting for resource"
 52  
      */
 53  
     private static final int ORACLE_00060 = 60;
 54  
     
 55  
 
 56  0
     protected final Logger LOG = Logger.getLogger(getClass());
 57  
 
 58  
     protected ExecutorService executor;
 59  
     protected PlatformTransactionManager txManager;
 60  
     
 61  
     /**
 62  
      * Constructs a ConcurrentJob instance.
 63  
      * @param txManager PlatformTransactionManager to use for transactions
 64  
      * @param executor the ExecutorService to use to process work items
 65  
      */
 66  0
     public ConcurrentJob(PlatformTransactionManager txManager, ExecutorService executor) {
 67  0
         this.txManager = txManager;
 68  0
         this.executor = executor;
 69  0
     }
 70  
 
 71  
     /**
 72  
      * Helper method for creating a TransactionTemplate initialized to create
 73  
      * a new transaction
 74  
      * @return a TransactionTemplate initialized to create a new transaction
 75  
      */
 76  
     protected TransactionTemplate createNewTransaction() {
 77  0
         TransactionTemplate tt = new TransactionTemplate(txManager);
 78  0
         tt.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
 79  0
         return tt;
 80  
     }
 81  
 
 82  
     /**
 83  
      * Template method that subclasses should override to obtain a set of available work items
 84  
      * and mark them as taken
 85  
      * @return a collection of available work items that have been marked as taken
 86  
      */
 87  
     protected abstract Collection<T> takeAvailableWorkItems();
 88  
 
 89  
     /**
 90  
      * Template method that subclasses should override to group work items into units of work
 91  
      * @param workItems list of work items to break into groups
 92  
      * @param result ProcessingResult to modify if there are any failures...this is sort of a hack because previously
 93  
      * failure to obtain a deliverer was considered a work item failure, and now this method has been factored out...
 94  
      * but the tests still want to see the failure
 95  
      * @return a collection of collection of work items
 96  
      */
 97  
     protected Collection<Collection<T>> groupWorkItems(Collection<T> workItems, ProcessingResult result) {
 98  0
         Collection<Collection<T>> groupedWorkItems = new ArrayList<Collection<T>>(workItems.size());
 99  0
         for (T workItem: workItems) {
 100  0
             Collection<T> c = new ArrayList<T>(1);
 101  0
             c.add(workItem);
 102  0
             groupedWorkItems.add(c);
 103  0
         }
 104  0
         return groupedWorkItems;
 105  
     }
 106  
 
 107  
     /**
 108  
      * Template method that subclasses should override to process a given work item and mark it
 109  
      * as untaken afterwards
 110  
      * @param item the work item
 111  
      * @return a collection of success messages
 112  
      */
 113  
     protected abstract Collection<?> processWorkItems(Collection<T> items);
 114  
 
 115  
     /**
 116  
      * Template method that subclasses should override to unlock a given work item when procesing has failed.
 117  
      * @param item the work item to unlock
 118  
      */
 119  
     protected abstract void unlockWorkItem(T item);
 120  
 
 121  
     /**
 122  
      * Main processing method which invokes subclass implementations of template methods
 123  
      * to obtain available work items, and process them concurrently
 124  
      * @return a ProcessingResult object containing the results of processing
 125  
      */
 126  
     public ProcessingResult run() {
 127  0
         LOG.debug("[" + new Timestamp(System.currentTimeMillis()).toString() + "] STARTING RUN");
 128  
 
 129  0
         final ProcessingResult result = new ProcessingResult();
 130  
 
 131  
         // retrieve list of available work items in a transaction
 132  0
         Collection<T> items = null;
 133  
         try {
 134  0
             items = (Collection<T>)
 135  0
                 createNewTransaction().execute(new TransactionCallback() {
 136  
                     public Object doInTransaction(TransactionStatus txStatus) {
 137  0
                         return takeAvailableWorkItems();
 138  
                     }
 139  
                 });
 140  0
         } catch (DataAccessException dae) {
 141  
             // Spring does not detect OJB's org.apache.ojb.broker.OptimisticLockException and turn it into a
 142  
             // org.springframework.dao.OptimisticLockingFailureException?
 143  0
             OptimisticLockException optimisticLockException = Util.findExceptionInStack(dae, OptimisticLockException.class);
 144  0
             if (optimisticLockException != null) {
 145  
                 // anticipated in the case that another thread is trying to grab items
 146  0
                 LOG.info("Contention while taking work items");
 147  
             } else {
 148  
                 // in addition to logging a message, should we throw an exception or log a failure here?
 149  0
                 LOG.error("Error taking work items", dae);
 150  0
                 Throwable t = dae.getMostSpecificCause();
 151  0
                 if (t != null && t instanceof SQLException) {
 152  0
                     SQLException sqle = (SQLException) t;
 153  0
                     if (sqle.getErrorCode() == ORACLE_00054 && StringUtils.contains(sqle.getMessage(), "resource busy")) {
 154  
                         // this is expected and non-fatal given that these jobs will run again
 155  0
                         LOG.warn("Select for update lock contention encountered");
 156  0
                     } else if (sqle.getErrorCode() == ORACLE_00060 && StringUtils.contains(sqle.getMessage(), "deadlock detected")) {
 157  
                         // this is bad...two parties are waiting forever somewhere...
 158  
                         // database is probably wedged now :(
 159  0
                         LOG.error("Select for update deadlock encountered!");
 160  
                     }
 161  
                 }
 162  
             }
 163  0
             return result;
 164  0
         } catch (UnexpectedRollbackException ure) {
 165  
             // occurs against Mckoi... :(
 166  0
             LOG.error("UnexpectedRollbackException - possibly due to Mckoi");
 167  0
             return result;
 168  0
         } catch (TransactionException te) {
 169  0
             LOG.error("Error occurred obtaining available work items", te);
 170  0
             result.addFailure("Error occurred obtaining available work items: " + te);
 171  0
             return result;
 172  0
         }
 173  
 
 174  0
         Collection<Collection<T>> groupedWorkItems = groupWorkItems(items, result);
 175  
 
 176  
         // now iterate over all work groups and process each
 177  0
         Iterator<Collection<T>> i = groupedWorkItems.iterator();
 178  0
         List<Future> futures = new ArrayList<Future>();
 179  0
         while(i.hasNext()) {
 180  0
             final Collection<T> workUnit= i.next();
 181  
 
 182  0
             LOG.info("Processing work unit: " + workUnit);
 183  
             /* performed within transaction */
 184  
             /* executor manages threads to run work items... */
 185  0
             futures.add(executor.submit(new Callable() {
 186  
                 public Object call() throws Exception {
 187  0
                     ProcessingResult result = new ProcessingResult();
 188  
                     try {
 189  0
                         Collection<?> successes = (Collection<Object>)
 190  0
                             createNewTransaction().execute(new TransactionCallback() {
 191  
                                 public Object doInTransaction(TransactionStatus txStatus) {
 192  0
                                     return processWorkItems(workUnit);
 193  
                                 }
 194  
                             });
 195  0
                         result.addAllSuccesses(successes);
 196  0
                     } catch (Exception e) {
 197  0
                         LOG.error("Error occurred processing work unit " + workUnit, e);
 198  0
                         for (final T workItem: workUnit) {
 199  0
                             LOG.error("Error occurred processing work item " + workItem, e);
 200  0
                             result.addFailure("Error occurred processing work item " + workItem + ": " + e);
 201  0
                             unlockWorkItemAtomically(workItem);
 202  
                         }
 203  0
                     }
 204  0
                     return result;
 205  
                 }
 206  
             }));
 207  0
         }
 208  
 
 209  
         // wait for workers to finish
 210  0
         for (Future f: futures) {
 211  
             try {
 212  0
                 ProcessingResult workResult = (ProcessingResult) f.get();
 213  0
                 result.add(workResult);
 214  0
             } catch (Exception e) {
 215  0
                 String message = "Error obtaining work result: " + e;
 216  0
                 LOG.error(message, e);
 217  0
                 result.addFailure(message);
 218  0
             }
 219  
         }
 220  
 
 221  0
         LOG.debug("[" + new Timestamp(System.currentTimeMillis()).toString() + "] FINISHED RUN - " + result);
 222  
 
 223  0
         return result;
 224  
     }
 225  
     
 226  
     protected void unlockWorkItemAtomically(final T workItem) {
 227  
         try {
 228  0
             createNewTransaction().execute(new TransactionCallback() {
 229  
                 public Object doInTransaction(TransactionStatus txStatus) {
 230  0
                     LOG.info("Unlocking failed work item: " + workItem);
 231  0
                     unlockWorkItem(workItem);
 232  0
                     return null;
 233  
                 }
 234  
             });
 235  0
         } catch (Exception e2) {
 236  0
             LOG.error("Error unlocking failed work item " + workItem, e2);
 237  0
         }
 238  0
     }
 239  
 }