View Javadoc

1   /*
2    * $Id: TransactionCoordination.java 7976 2007-08-21 14:26:13Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.transaction;
12  
13  import org.mule.config.i18n.CoreMessages;
14  import org.mule.umo.TransactionException;
15  import org.mule.umo.UMOTransaction;
16  
17  import org.apache.commons.logging.Log;
18  import org.apache.commons.logging.LogFactory;
19  
20  public final class TransactionCoordination
21  {
22      protected static final Log logger = LogFactory.getLog(TransactionCoordination.class);
23  
24      private static final TransactionCoordination instance = new TransactionCoordination();
25  
26      private static final ThreadLocal transactions = new ThreadLocal();
27  
28      // @GuardedBy("this")
29      private int txCounter = 0;
30  
31      /** Do not instanciate. */
32      private TransactionCoordination()
33      {
34          super();
35      }
36  
37      public static TransactionCoordination getInstance()
38      {
39          return instance;
40      }
41  
42      public UMOTransaction getTransaction()
43      {
44          return (UMOTransaction) transactions.get();
45      }
46  
47      public void unbindTransaction(UMOTransaction transaction) throws TransactionException
48      {
49          try
50          {
51              UMOTransaction oldTx = (UMOTransaction) transactions.get();
52              if (oldTx != null && !oldTx.equals(transaction))
53              {
54                  throw new IllegalTransactionStateException(CoreMessages.transactionCannotUnbind());
55              }
56          }
57          finally
58          {
59              transactions.set(null);
60  
61              synchronized (this)
62              {
63                  if (txCounter > 0)
64                  {
65                      txCounter--;
66                  }
67              }
68          }
69      }
70  
71      public void bindTransaction(UMOTransaction transaction) throws TransactionException
72      {
73          UMOTransaction oldTx = (UMOTransaction) transactions.get();
74          if (oldTx != null)
75          {
76              throw new IllegalTransactionStateException(CoreMessages.transactionAlreadyBound());
77          }
78  
79          transactions.set(transaction);
80  
81          synchronized (this)
82          {
83              txCounter++;
84  
85              if (logger.isDebugEnabled())
86              {
87                  logger.debug("Binding new transaction (" + txCounter + ")");
88              }
89          }
90      }
91  
92  }