01: /*
02: * $Id: TransactionCoordination.java 10489 2008-01-23 17:53:38Z dfeist $
03: * --------------------------------------------------------------------------------------
04: * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
05: *
06: * The software in this package is published under the terms of the CPAL v1.0
07: * license, a copy of which has been included with this distribution in the
08: * LICENSE.txt file.
09: */
10:
11: package org.mule.transaction;
12:
13: import org.mule.api.transaction.Transaction;
14: import org.mule.api.transaction.TransactionException;
15: import org.mule.config.i18n.CoreMessages;
16:
17: import org.apache.commons.logging.Log;
18: import org.apache.commons.logging.LogFactory;
19:
20: public final class TransactionCoordination {
21: protected static final Log logger = LogFactory
22: .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: super ();
34: }
35:
36: public static TransactionCoordination getInstance() {
37: return instance;
38: }
39:
40: public Transaction getTransaction() {
41: return (Transaction) transactions.get();
42: }
43:
44: public void unbindTransaction(Transaction transaction)
45: throws TransactionException {
46: try {
47: Transaction oldTx = (Transaction) transactions.get();
48: if (oldTx != null && !oldTx.equals(transaction)) {
49: throw new IllegalTransactionStateException(CoreMessages
50: .transactionCannotUnbind());
51: }
52: } finally {
53: transactions.set(null);
54:
55: synchronized (this ) {
56: if (txCounter > 0) {
57: txCounter--;
58: }
59: }
60: }
61: }
62:
63: public void bindTransaction(Transaction transaction)
64: throws TransactionException {
65: Transaction oldTx = (Transaction) transactions.get();
66: if (oldTx != null) {
67: throw new IllegalTransactionStateException(CoreMessages
68: .transactionAlreadyBound());
69: }
70:
71: transactions.set(transaction);
72:
73: synchronized (this ) {
74: txCounter++;
75:
76: if (logger.isDebugEnabled()) {
77: logger.debug("Binding new transaction (" + txCounter
78: + ") " + transaction);
79: }
80: }
81: }
82:
83: }
|