Introduce TransactionHelper, a utility class for retrying the supplied transactional...
[pithos] / src / gr / ebs / gss / server / rest / TransactionHelper.java
1 /*
2  * Copyright 2009 Electronic Business Systems Ltd.
3  *
4  * This file is part of GSS.
5  *
6  * GSS is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * GSS is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with GSS.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 package gr.ebs.gss.server.rest;
20
21 import java.util.concurrent.Callable;
22
23 import javax.ejb.EJBTransactionRolledbackException;
24
25 import org.apache.commons.logging.Log;
26 import org.apache.commons.logging.LogFactory;
27
28 /**
29  * A helper class that provides a method for repeatedly trying a transaction
30  * that is rolled back due to optimistic locking exceptions.
31  *
32  * @author  past
33  */
34 public class TransactionHelper<T> {
35         /**
36          * The logger.
37          */
38         private static Log logger = LogFactory.getLog(TransactionHelper.class);
39
40         /**
41          * Number of times to retry a transaction that was rolled back due to
42          * optimistic locking.
43          */
44         private static final int TRANSACTION_RETRIES = 10;
45
46         /**
47          * Execute the supplied command until it completes, ignoring
48          * EJBTransactionRolledbackException. Try at least TRANSACTION_RETRIES
49          * times before giving up.
50          *
51          * @param command the command to execute
52          * @return the value returned by the command
53          * @throws Exception any other exception thrown by the command
54          */
55         public T tryExecute(Callable<T> command) throws Exception {
56                 T returnValue = null;
57                 for (int i = 0; i < TRANSACTION_RETRIES; i++) {
58                         try {
59                                 returnValue = command.call();
60                                 break;
61                         } catch(EJBTransactionRolledbackException trbe) {
62                                 if (i == TRANSACTION_RETRIES - 1)
63                                         throw trbe;
64                         } catch (Exception e) {
65                                 throw e;
66                         }
67                         logger.debug("Transaction retry: " + (i+1));
68                 }
69                 return returnValue;
70         }
71 }