Skip Headers

Oracle® Containers for J2EE Resource Adapter Administrator's Guide 10g Release 3 (10.1.3) B14436-01 |
| Home | Solution Area | Contents | Index

Previous | Next |

# 4 Transaction Management

This chapter covers key aspects of transactions and the J2CA transaction management contract for outbound connections. This contract leverages the standard J2EE programming model for transaction management, allowing access by an application to multiple disparate EISs through standard interfaces in the context of a single, coordinated transaction.

The following topics are covered here:

- Introduction to Transactions and Transaction Management

- Overview of Key Interfaces Used in Transaction Management

- Transaction Support in the OC4J Connector Implementation

- OC4J Transaction Setup and Cleanup

- Understanding Connection Sharing in OC4J

- Understanding and Configuring Transaction Recovery

- Understanding J2CA Connection Wrapping

For additional information about OC4J transaction support, see the Java Transaction API chapter of the Oracle Containers for J2EE Services Guide.

## Introduction to Transactions and Transaction Management

The topic of transactions concerns how updates and manipulations of data are managed in order to ensure the integrity of the data. A transaction may involve just a single EIS or multiple EISs. Particularly in the latter case, strict rules must be followed to coordinate the updates and ensure that data is not left in an inconsistent state in the event of problems during the transaction. For example, if a transaction involves transferring money from one account to another, you want to avoid a situation where the balance is updated in only one account.

The following subsections provide a quick introduction or refresher for transactions and transaction management:

- Transaction Characteristics and Scopes

- Relationship with Enterprise JavaBeans Technology

- Relationship with Java Transaction API Technology

- Local Transaction Management

- Global Transaction Management

- Resource Adapter Configuration for Level of Transaction Support

### Transact ion Characteristics and Scopes

A transaction is a unit of work, typically consisting of multiple operations, between an application component and one or more EISs to update or manipulate data. Transactions must have four basic characteristics: atomicity (ensuring that either all operations of a transaction are completed or all are rolled back), consistency (of the data), isolation (preventing one transaction from seeing any results of other transactions until those transactions are complete), and durability (ensuring that committed transactions are persisted even in the event of system failure after the commit operation). It is a convention to refer to these collectively by the acronym ACID.

A resource manager can support no transactions, local transactions, or global transactions (also known as distributed transactions or XA transactions). A global transaction is managed by an external transaction manager, such as through a Java Transaction API (JTA) implementation. A local transaction is typically managed internally within a single resource manager. (It can optionally can be managed by an external transaction manager, but this probably results in needless overhead.) Executing a transaction to a single resource manager, verifying the ACID properties, then committing the transaction is known as a one-phase commit protocol. To ensure complete data consistency and integrity, a transaction across multiple resource managers must use a two-phase commit protocol, consisting of a "prepare" phase and a "commit" phase. Updates are not committed to any resource manager unless all resource managers are prepared for updates.

All data manipulations that are part of a single transaction share a transaction context.

### Relationship with Enterprise JavaBeans Technology

Enterprise JavaBeans technology, designed for data integrity and security, plays a large role in the overall transaction model of the J2EE platform. The J2EE Connector Architecture is tied closely to the EJB architecture, which is designed to handle transaction management for an application. A typical J2EE application executing transactions with one or more EISs will do so through EJB components.

In EJB techn ology, the demarcation (essentially, the beginning and end) of a transaction can be managed either by a bean, in a model known as bean-managed transaction demarcation, or by the container, in a model known as container-managed transaction demarcation. Entity beans, designed for data access, must use container-managed transaction demarcation. Session beans can use either model.

Transactions associated with J2CA connections are intended to seamlessly extend EJB transactions, regardless of which demarcation model is used. If an EJB method executes in the scope of a transaction, all work done by an EIS on behalf of the EJB is within the scope of the transaction, assuming the EIS supports global transactions. (Also see "OC4J Support for Last-Resource-Commit Optimization" for information about how a single EIS that does not support global transactions can be included in a global transaction.)

See the Oracle Containers for J2EE Enterprise JavaBeans Developer's Guide for details about EJBs in OC4J.

### Relatio nship with Java Transaction API Technology

The Java Transaction API (JTA) is the transaction management vehicle of the J2EE platform. Any typical J2EE application performing global transactions, usually through EJBs and using resource adapters to access EISs, employs JTA. Use of the JTA involves a transaction manager that is external to the resource managers and coordinates the overall transaction. The JTA is a set of interfaces between a transaction manager and the entities involved in a transaction—the application component, application server, and resource manager.

Important features provided by the JTA include two-phase commit, introduced earlier, which includes transaction recovery in the event that a resource manager fails during a transaction.

Key JTA interfaces, implemented by OC4J, include the `Transaction`, `TransactionManager`, and `UserTransaction` interfaces of the `javax.transaction` package. A `Transaction` object represents a transaction and has methods, such as `commit()` and `rollback()`, to allow an application to perform operations in the transaction. A `TransactionManager` object has methods allowing J2EE containers such as OC4J to manage the boundaries of a transaction, for container-managed transaction demarcation. A `UserTransaction` object has methods allowing an application to manage the boundaries of a transaction, for bean-managed transaction demarcation. An application component would use JNDI to look up a `UserTransaction` object. See "Implemented by Transaction Managers: UserTransaction and TransactionManager" for additional information.

The JTA `javax.transaction.xa.XAResource` interface is implemented by resource adapter providers to represent resources, such as EISs, used in global transactions controlled by an external transaction manager. The transaction manager obtains an `XAResource` object for each EIS connection that is participating in the transaction, and it can associate and disassociate each resource with the transaction. See "Implemented by Resource Adapters: XAResource and LocalTransaction" for additional information.

Refer to Oracle Containers for J2EE Services Guide for additional information about the Java Transaction API.

### Local Tran saction Management

A local transaction is one that is specific to a single resource manager, and is created and committed against this resource manager. The transaction can be demarcated by an application component or by the container.

Demarcation by an application component would involve EIS-specific APIs, such as, for example, methods of the CCI `LocalTransaction` interface (for a resource adapter that implements the CCI) or methods of the JDBC `java.sql.Connection` interface, such as `commit()` and `rollback()` (for a JDBC driver).

Demarcation by a container would involve methods of the SPI `LocalTransaction` interface.

Note: For container-managed transaction demarcation, where only one resource manager is involved in a JTA transaction, a container has two choices: Use its transaction manager to manage the transaction, using one-phase-commit optimization. This is what OC4J does. (See "Highlights of Required Transaction Support".) Let the resource manager coordinate the transaction internally, using a local transaction of the resource manager without involving an external transaction manager.

### Global Tra nsaction Management

Global transactions typically use JTA `XAResource` objects, as noted earlier. This interface is based on the industry standard X/Open transaction model. The OC4J transaction manager coordinates all resource managers involved in the transaction.

For data integrity and consistency, `XAResource` objects support the two-phase-commit protocol to ensure that a transaction is committed successfully across all the resource managers, or is committed to none. In this protocol, the OC4J transaction manager calls the `XAResource` `prepare()` method on each resource manager to notify it of a pending commit. Only if each resource manager can be reached, and agrees to the commit, will the transaction manager proceed by calling the `XAResource` `commit()` method on each resource manager to commit the transaction. If, during the prepare phase, any resource manager cannot be reached or vetoes the commit, then the transaction manager aborts the transaction by calling the `XAResource` `rollback()` method on each resource manager.

### Resource Ada pter Configuration for Level of Transaction Support

In the `ra.xml` file supplied by a resource adapter provider, the level of transaction support of a resource adapter is indicated in the `<transaction-support>` element. According to version 1.5 of the J2EE Connector Architecture Specification, this is a subelement of an `<outbound-resourceadapter>` element and supports the values `NoTransaction`, `LocalTransaction`, or `XATransaction`, as in the following example for global transaction support:

    <outbound-resourceadapter>
       ...
       <transaction-support>XATransaction</transaction-support>
       ...
    </outbound-resourceadapter>

(In version 1.0 of the J2EE Connector Architecture Specification, `<transaction-support>` is a subelement of the `<resourceadapter>` element.)

Support levels are as follows:

- `NoTransaction` means the resource adapter supports no transactions at all, neither global transactions nor local transactions. Data can be written or updated, but no ACID properties are possible across multiple interactions with the EIS.

- `LocalTransaction` means the resource adapter supports local transactions, implementing the SPI `LocalTransaction` interface, but does not support global transactions.

- `XATransaction` means the resource adapter supports global transactions as well as local transactions, implementing the SPI `LocalTransaction` interface and the `XAResource` interface.

If the transaction support level of the resource adapter is `XATransaction`, then the J2CA container will call the `getXAResource()` method on the `ManagedConnection` instance when an `XAResource` object is needed to enlist the connection with a global transaction. If the transaction support level of the resource adapter is `LocalTransaction`, then the container will call the `getLocalTransaction()` method to get a `LocalTransaction` object. If the local transaction-level connection needs to be enlisted in a global transaction, then the container will create an emulated `XAResource`. The emulated `XAResource` gets enlisted and allows the local transaction-level connection to participate in a global transaction through the `LocalTransaction` object (with restrictions).

## Overview of Key Interfaces Used in Transaction Management

The following sections summarize key J2CA and Java Transaction API interfaces that are used in transaction management:

- Implemented by Resource Adapters: XAResource and LocalTransaction

- Implemented by Transaction Managers: UserTransaction and TransactionManager

- Implemented by OC4J: ConnectionEventListener Interface

### Implem ented by Resource Adapters: XAResource and LocalTransaction

Each of the following interfaces, implemented by resource adapter providers, plays an important role in the transaction management contract:

- `javax.transaction.xa.XAResource`

- `javax.resource.spi.LocalTransaction`

`XAResource` or `LocalTransaction` instances can be obtained from a managed connection, through methods specified in the SPI `ManagedConnection` interface. OC4J always obtains a `ManagedConnection` object from the resource adapter, through the resource adapter `ManagedConnectionFactory` object, when an application component requests a connection. This is regardless of whether work will be in the context of a transaction. The `ManagedConnection` object represents a physical EIS connection and may be either newly created or obtained from a connection pool. (The process of obtaining a managed connection is described in "Summary of the Connection Management Contract".) Classes implementing `ManagedConnectionFactory` and `ManagedConnection` are supplied by the resource adapter provider.

The `ManagedConnection` interface specifies the following methods:

- `XAResource getXAResource()`

- `LocalTransaction getLocalTransaction()`

If the application component requesting a connection is in a global transaction context, and the resource adapter supports the `XATransaction` transaction support level, then OC4J calls the `getXAResource()` method to obtain an `XAResource` object from the managed connection. OC4J then enlists the `XAResource` object with the OC4J transaction manager. (The transaction manager obtains an `XAResource` object for each connection participating in a global transaction.) An `XAResource` object enables the EIS to participate in transactions that are controlled by an external transaction manager, such as the OC4J transaction manager. The transaction manager uses the `XAResource` object to communicate information about the transaction—such as association, completion, and recovery—to the EIS.

Key `XAResource` methods include the following:

- `void start(Xid, ...)` to start the work of a transaction branch

- `void end(Xid, ...)` to end the work of a transaction branch

- `void prepare(Xid, ...)` to execute the "prepare" phase of a two-phase commit

- `void commit(Xid, ...)` to execute the "commit" phase of a two-phase commit

- `void rollback(Xid, ...)` to roll back the transaction

Each of these takes a `javax.transaction.xa.Xid` instance to identify the transaction.

If the application component requesting a connection is in a local transaction context, or the application component is in a global transaction context but the resource adapter supports only the `LocalTransaction` transaction support level, then OC4J calls the `getLocalTransaction()` method to obtain a `LocalTransaction` object from the managed connection. A `LocalTransaction` object enables OC4J to manage a local transaction with the EIS.

The SPI `LocalTransaction` interface specifies three methods:

- `void begin()` to begin the local transaction

- `void commit()` to commit the local transaction

- `void rollback()` to roll back the local transaction

Note: Do not confuse the SPI `LocalTransaction` interface, implemented by a resource adapter provider, with the CCI `LocalTransaction` interface, optionally implemented for client-side use. The CCI interface is for application-level local transaction demarcation. The SPI interface is used by the J2EE container for local transaction management. Both interfaces define the same methods, however.

### Implemented by Tra nsaction Managers: UserTransaction and TransactionManager

The following interfaces are implemented by transaction managers, such as the OC4J transaction manager:

- `javax.transaction.UserTransaction`

- `javax.transaction.TransactionManager`

The OC4J transaction manager allows global transactions to be supported across multiple EISs. A global transaction can be started either by an application component (typically an EJB) in a component-managed (bean-managed) scenario, or by OC4J in a container-managed scenario. In the former case, the component would use a `UserTransaction` object, which includes the following methods:

- `void begin()` to create a transaction and associate it with the current thread

- `void commit()` to commit the transaction associated with the current thread

- `void rollback()` to roll back the transaction associated with the current thread

Note: In a global transaction scenario, where an application component has called the `begin()` method of a `UserTransaction` object (used for bean-managed transaction demarcation), OC4J enlists a resource manager `XAResource` object with the OC4J transaction manager whenever a connection handle for that resource manager is returned to the application. And OC4J disassociates the `XAResource` object from the transaction manager when the application component releases or closes the connection.

When a global transaction is started by OC4J in a container-managed scenario, OC4J manages the transaction through a `TransactionManager` object, which includes the following methods:

- `void begin()` to create a transaction and associate it with the current thread

- `void commit()` to commit the transaction associated with the current thread

- `void rollback()` to roll back the transaction associated with the current thread

- `Transaction suspend()` to suspend and return a transaction (`Transaction` object) that was associated with the current thread, and disassociate the resource from the transaction

- `void resume(Transaction)` to resume the association of the current thread with the transaction (represented by the `Transaction` object), and also reassociate the resource with the transaction

Once the transaction begins, and an application component requests a connection, the connection management mechanism is executed as described in "Summary of the Connection Management Contract".

### Implemented by OC4J: ConnectionEventListener Interface

OC4J implements the SPI `ConnectionEventListener` interface, which allows notifications from EISs regarding connection and transaction status, and registers each listener instance with the appropriate managed connection factory.

OC4J relies on notification when a connection is closed, to accomplish connection cleanup and any transaction cleanup required as a result of closing the connection. The following `ConnectionEventListener` method is called by the resource adapter:

- `void connectionClosed(ConnectionEvent)`

For local transactions, OC4J relies on notifications when a transaction is started, committed, or rolled back. The following `ConnectionEventListener` methods are called by the resource adapter:

- `void localTransactionStarted(ConnectionEvent)`

- `void localTransactionCommitted(ConnectionEvent)`

- `void localTransactionRolledback(ConnectionEvent)`

Each of these methods takes an SPI `ConnectionEvent` object that represents the event that OC4J is being notified of.

## Transaction Support in the OC4J Connector Implementation

The following sections summarize highlights of the OC4J implementation of J2CA transaction management:

- Highlights of Required Transaction Support

- Highlights of Optional Transaction Support

- OC4J Configuration for Transaction Recovery

### Highlights of Required Transaction Support

The following key OC4J features for resource adapters reflect requirements of the J2EE Connector Architecture:

- OC4J reads `<transaction-support>` elements of an `ra.xml` file to determine the level of transactions supported by the declared resource adapters.

- OC4J detects and prevents any occurrences of illegal transaction demarcation in an application component, such as an attempt to begin a global transaction while a local transaction is still in progress.

- As described earlier, OC4J supports the local transactions contract based on the SPI `LocalTransaction` interface, and supports global transactions that are based on functionality of the `XAResource` interface. (See "Implemented by Resource Adapters: XAResource and LocalTransaction".)

- OC4J can use the one-phase-commit protocol for transactions using a single physical connection to a resource manager. One-phase-commit optimization, supported by OC4J, is for the scenario of a global transaction context where all logical connections in the transaction use the same physical connection to the same EIS, which must support at least one-phase-commit protocol. (Multiple logical connections may all point to the same physical connection due to connection sharing, for example, assuming all connections use the same data source and user name.) In this case, OC4J uses only the "commit" phase of the two-phase-commit protocol. The "prepare" phase is skipped.

- As noted earlier, OC4J implements the SPI `ConnectionEventListener` interface, and relies on notifications from the listener for local transaction starts, commits, and rollbacks. For a global transaction, OC4J relies on notifications for connection-closed events. (See "Implemented by OC4J: ConnectionEventListener Interface".)

- OC4J detects incomplete local transactions. For example, if a stateless session bean starts a local transaction through a method invocation, but returns from the method without completing the transaction, then OC4J terminates the session and throws an exception.

- If an application component terminates due to an exception during a method invocation, OC4J resets all local transactions in progress and resets any client-specific state.

- OC4J supports connection sharing. See "Understanding Connection Sharing in OC4J".

### Highlights of Optional Transaction Support

This section discusses OC4J support for features that are optional or beyond the scope of the J2CA specification. The following topics are covered:

- OC4J Support for Lazy Enlistment of Connections in a Transaction

- OC4J Support for Last-Resource-Commit Optimization

- Unsupported Transaction Scenarios

- OC4J Checking for Illegal Transaction Demarcation

#### OC4J Supp ort for Lazy Enlistment of Connections in a Transaction

Typically, when an application component requests a connection handle in the context of a transaction, the connection is automatically, or "eagerly", enlisted in the transaction. This is true even if the connection is ultimately unused, which results in unnecessary overhead.

With "lazy" enlistment, a new connection is enlisted in the transaction only if it is actually used in the transaction—in other words, only if data is transmitted through the connection.

Both a resource adapter and an application server must support lazy enlistment for this feature to be usable. The OC4J connection manager supports this feature through its implementation of the SPI `LazyEnlistableConnectionManager` interface, so you can use lazy enlistment with any resource adapter that implements the `LazyEnlistableManagedConnection` interface for its managed connections. A managed connection calls the `lazyEnlist()` method on the connection manager, which results in enlistment of the connection only if it is used.

Both the resource adapter and OC4J are capable of determining whether the other implements the requisite interface. Neither attempts lazy enlistment if the other does not support it.

#### OC4J Sup port for Last-Resource-Commit Optimization

The OC4J 10.1.3 implementations of the Java Transaction API and J2EE Connector Architecture support last-resource-commit optimization for a situation where one (and only one) resource adapter supporting `LocalTransaction` (one-phase commits) is to be included in a global transaction with resource adapters supporting `XATransaction` (two-phase commits). Essentially, last resource commit optimization allows for a single non-XA-compliant resource to participate in an XA transaction, in the root OC4J process. If more than one non-XA-compliant resource is enlisted in the transaction, then an exception is thrown from the enlistment attempt.

For resource adapters, this optimization is accomplished by emulating an `XAResource` object, using an instance of the type `EmulatedXAResource` to represent the one-phase-commit resource adapter, with the resource adapter receiving notifications through the emulated XA resource. If there is any attempt to include a second resource adapter supporting only one-phase-commit protocol, the OC4J transaction manager throws an exception.

The transaction manager takes the following steps when it receives a request to commit a global transaction that includes one emulated XA resource:

1. It invokes a `prepare()` call on each of the two-phase-commit resources.

2. If all of the two-phase-commit resources are successfully prepared, then `commit()` (one-phase) is called on the emulated XA resource.

3. If the one-phase commit on the emulated XA resource completes successfully, then the transaction manager logs a decision to commit the global transaction and calls `commit()` on each of the two-phase-commit resources.

   Or else, if the one-phase commit on the emulated XA resource fails, then the transaction manager logs a decision to roll back the global transaction and calls rollback() on each of the two-phase-commit resources.

See "Last Resource Commit" under Oracle Containers for J2EE Services Guide for more information.

Notes Regarding Last-Resource-Commit Optimization Be aware of the following regarding last-resource-commit optimization:

- An emulated XA resource also implements the `SinglePhaseResource` interface, which is what signals its status as an emulated resource to OC4J.

- Last-resource-commit optimization becomes problematic if a failure occurs after `commit()` is called on the emulated XA resource but before the transaction manager receives the result of that call. In such a case, it is not possible to assure that the result of the global transaction will be atomic.

- With emulated XA resources, transaction recovery is not applicable.

- The transaction manager treats an emulated XA resource as a standard XA resource if logging is disabled in the transaction manager (in which case there can be no recovery).

#### Unsupported Transaction Scenarios

OC4J, in accordance with the J2EE Connector Architecture, does not generally support attempts to include multiple non-XA resource adapters within a single transaction. (Note that the discussion in the preceding section, "OC4J Support for Last-Resource-Commit Optimization", specifies a single non-XA resource adapter only.)

Note: There are exceptions. If logging is disabled in the transaction manager, in which case recovery is not possible, then multiple one-phase-commit resources are allowed to participate in a transaction. Also, multiple emulated XA resources may be used in a transaction in testing scenarios, such as for performance testing.

Also, we do not recommend that you attempt a global transaction in which a resource adapter is at `XATransaction` support level but supports only one-phase commit (although a one-phase-commit resource can provide an `XAResource` object to emulate global transactions). The lack of true support for two-phase commit would not be known until it was time to commit the global transaction.

#### OC4J Checking for Illegal Transaction Demarcation

OC4J, through its implementation of the SPI `ConnectionEventListener` interface, flags cases of illegal transaction demarcation.

As an example, assume an EJB using bean-managed demarcation begins a local transaction (such as by using the CCI `LocalTransaction` interface, if that is supported by the resource adapter). Further assume that the EJB, before completing the local transaction, tries to begin a global transaction through a `begin()` call on a `UserTransaction` object. The resource adapter will have sent a "local transaction started" message to OC4J, but because OC4J will not yet have received a "local transaction committed" or "local transaction rolled back" notification at the point when the attempt is made to start a global transaction, OC4J will throw an exception on the `UserTransaction` `begin()` call.

### OC4J Configuration for Transaction Recovery

Little configuration is required in OC4J for the transaction management contract. Functionality is largely behind the scenes. However, transaction recovery requires the configuration of a special user name and password. If a failure occurs during transaction processing, the OC4J recovery manager may need to contact an EIS, which will usually require special credentials, to inquire about any transactions that are in doubt. See "Understanding and Configuring Transaction Recovery".

## OC4J Transaction Setup and Cleanup

The following sections describe how OC4J sets up before transactions and cleans up afterward, for the possible transaction levels and resource adapter support levels:

- Global Transaction Setup and Cleanup

- Local Transaction Setup and Cleanup

### Global Transaction Setup and Cleanup

This section covers OC4J transaction setup and cleanup for global transactions, either where all involved resource adapters are at the `XATransaction` support level, or where last-resource-commit optimization is used, as discussed in "OC4J Support for Last-Resource-Commit Optimization". (In the scenario of a global transaction with a resource adapter supporting only `NoTransaction`, OC4J completes connection setup as described in "Summary of the Connection Management Contract", but does not perform any steps for transaction setup.)

If a connection allocation request is invoked from a J2EE application component that is within a global transaction context, and the resource adapter provides `XATransaction` support level (or there is a last-resource-commit scenario, as will be noted), OC4J performs the following steps to enlist the work done in the connection to the transaction manager:

1. Obtains a managed connection from the resource adapter—either a newly created managed connection or an existing one from the connection pool. See "Summary of the Connection Management Contract" for details.

2. Obtains an `XAResource` object from the managed connection. The OC4J transaction manager will use the `XAResource` object to provide any transaction notifications to the resource manager.

   Note: For the resource adapter supporting only `LocalTransaction` in a last-resource-commit scenario, OC4J obtains, or if necessary creates, an `EmulatedXAResource` object associated with the managed connection, instead of obtaining an `XAResource` object directly from the managed connection. In this case, substitute `EmulatedXAResource` for `XAResource` in the steps that follow.

3. Enlists the `XAResource` object to the OC4J transaction manager.

4. Invokes the `start()` method of the `XAResource` object. For any work done through the connection, the resource manager is instructed to associate the work with a transaction branch.

5. Creates a connection handle from the managed connection and hands it back to the application component.

When the application component closes the connection handle, the resource adapter sends a `ConnectionClosed` event to OC4J. If there are no outstanding connection handles for the underlying managed connection, OC4J calls the `end()` method of the `XAResource` object to inform the resource manager that any further operations on the managed connection will not be associated with the global transaction (performed by the OC4J transaction manager).

### Local Transaction Setup and Cleanup

This section covers OC4J transaction setup and cleanup for local transactions, where all involved resource adapters are at either the `LocalTransaction` or `XATransaction` support level. (In the scenario of a local transaction with a resource adapter supporting only `NoTransaction`, OC4J completes connection setup as described in "Summary of the Connection Management Contract", but does not perform any steps for transaction setup or cleanup.)

A local transaction can be started by OC4J, similarly to what is described in "Global Transaction Setup and Cleanup". Alternatively, a J2EE application component can explicitly begin and end a local transaction through the use of an application-level transaction demarcation interface. The particular process used in starting a local transaction depends on the connection interface being used. For resource adapters that implement CCI as the client interface, an application component can obtain a CCI `LocalTransaction` object from a CCI `Connection` object, through the `getLocalTransaction()` method.

Regardless of the particulars of the client-side API, the following steps are executed between the resource adapter and OC4J when a local transaction is started:

1. The resource adapter detects the request from the application component to start the local transaction. For example, in CCI this is when the application component invokes the `begin()` method of the CCI `LocalTransaction` object.

2. The resource adapter notifies OC4J that a local transaction is starting. OC4J relies on this notification in order to provide appropriate services.

3. The resource adapter executes an EIS-specific process to start the local transaction.

Similarly, an application component can explicitly end a local transaction by using an API provided by the resource adapter. As is the case when starting a local transaction, which particular methods to use in ending a local transaction depends on the connection interface being used.

Here is what happens between the resource adapter and OC4J when a local transaction is ended:

1. The resource adapter detects the request from the application component to end the local transaction. For example, in CCI this is when the application component invokes the `commit()` or `rollback()` method of the CCI `LocalTransaction` object.

2. The resource adapter notifies OC4J that a local transaction has ended. OC4J will then update its internal states accordingly.

3. The resource adapter executes an EIS-specific process to commit or roll back the local transaction on the EIS.

## Under standing Connection Sharing in OC4J

Connection sharing, specified in the J2EE Connector Architecture, allows multiple connection handles to be shared between multiple application components within a single transaction. This allows better performance and more efficient use of resources, and helps avoid resource manager lock contentions and read-isolation problems. The following sections discuss this feature:

- Conditions for Connection Sharing

- Connection Sharing Scenario

### Conditions for Connection Sharing

This section discusses conditions for connection sharing in OC4J:

- General Conditions for Connection Sharing

- Restriction on Connection Sharing for NoTransaction Support Level

#### General Conditions for Connection Sharing

When a new connection is requested by a J2EE application component, OC4J will attempt to return a new connection handle from an existing physical connection in the connection pool if the following conditions are satisfied:

- The connection request is for the same resource manager as is accessed through the existing physical connection, and uses the same data source.

- The connection request has the same properties as the physical connection, such as security attributes, isolation levels, character settings, and localization.

- The application component requesting the connection is in the same transaction scope as the application component currently using the physical connection.

- The application component has a "shareable" scope so that physical connections obtained from the resource manager can be shared between multiple logical connections. This is true by default, or can be explicitly specified under the applicable `<resource-ref>` element in the standard `ejb-jar.xml` or `web.xml` configuration file. In the following example, the application component can look up a connection factory from the JNDI location `eis/myEIS`, as specified in the `<res-ref-name>` element, for creating logical connection handles to the EIS. With the value of the `<res-sharing-scope>` element being declared as `shareable`, multiple connection handles in the application component can share a single physical connection, provided that the other conditions for connection sharing are met.

      <resource-ref>
         <res-ref-name>eis/myEIS</res-ref-name>
         <res-type>javax.sql.DataSource</res-type>
         <res-auth>Application</res-auth>
         <res-sharing-scope>shareable</res-sharing-scope>
      </resource-ref>

  A setting of `unshareable` disables sharing. Note that it is permissible for one or more components to declare connections from a resource to be shareable, while one or more other components declare connections from the same resource to be unshareable.

Notes: The use of a single shared connection, as opposed to multiple physical connections, is transparent to the application. Applications must not make assumptions about shared connections being used. Unless a resource manager is marked as unshareable, connections to it must be used in a shareable way, avoiding such actions as modifying security attributes, isolation levels, character settings, and localization.

#### Restriction on Connection Sharing for NoTransaction Support Level

Connection sharing is not supported for a resource adapter with transaction support level `NoTransaction`.

### Connection Sharing Scenario

This section describes a sample scenario for connection sharing. Assume you have an application with two EJB session beans: EJB1 and EJB2. Both use the same resource adapter, capable of local transactions, to connect to the same EIS within a single local transaction. The EIS is configured to be shareable, or is by default. Because a local transaction is always associated with a single physical connection, EJB1 and EJB2 in this scenario share the same physical connection under the local transaction scope.

Consider the following actions:

1. The client application calls a method on EJB1 with no transaction context. The method implementation in EJB1 uses container-managed transaction demarcation and requests a connection to the EIS.

2. The connection is obtained, at which point OC4J starts a local transaction. This transaction is associated with the managed connection object from which the connection handle was obtained, where the managed connection object represents the physical connection. Work performed by EJB1 on the EIS through the connection is included in the local transaction context.

3. EJB1 calls a method on EJB2, and the method implementation in EJB2 requests a connection to the EIS.

4. OC4J returns a connection handle to EJB2 using the same managed connection object as for the connection requested by EJB1. OC4J also maintains, across the method call from EJB1 to EJB2, an association between this managed connection object and the local transaction context. Work performed by EJB2 on the EIS through the connection is included in the local transaction context. Note that connection state, such as any open cursors, can therefore be maintained across method calls between EJB1 and EJB2 in this scenario.

   Note that if EJB2 calls the `close()` method on the connection handle before its method called from EJB1 has completed, OC4J does not initiate any cleanup on the physical connection at this time. This is because there is still an incomplete local transaction associated with the physical connection.

   When EJB1 regains control, it can still use the connection handle, assuming it had not also called the `close()` method.

5. Now assume EJB1 eventually calls the `close()` method on its connection handle. Because there is still an incomplete local transaction associated with the physical connection, OC4J does not initiate any cleanup on the physical connection at this time. It must still complete the local transaction process.

6. When the original method call from the client application completes, OC4J commits the local transaction.

7. The managed connection object does a cleanup of its local transaction state.

8. OC4J returns the physical connection to the pool

## Understanding and Configuring Transaction Recovery

This section discusses OC4J support for two-phase-commit recovery for resource managers accessed through outbound connections.

The goal of transaction recovery is to maintain data integrity when data manipulation with one EIS fails during a multiple-EIS (global) transaction. Transaction recovery is therefore not applicable for local or one-phase-commit transactions.

The following topics are covered:

- Understanding XA Recovery in OC4J

- Configuring XA Recovery in OC4J

### Underst anding XA Recovery in OC4J

When OC4J halts unexpectedly or loses the connection to a resource manager during a transaction, it enters a recovery mode (depending on the state of the transaction) where it attempts steps to complete the transaction that was in progress at the time of the failure. Responsibility for recovery is delegated to the OC4J recovery manager. The application itself is not involved.

The first step in XA recovery is to determine the transaction state and then attempt to acquire the necessary `XAResource` objects if the transaction state mandates recovery. If recovery is necessary, OC4J then tries to reestablish connection to the EISs as soon as possible. This requires sign-on information—user name and password for applicable connection factories—in the following circumstances:

- The application uses component-managed sign-on, where the application provides sign-on information that is invisible to OC4J.

- The EIS requires transaction recovery to be accomplished only through a special, privileged user account that is different from the account that the J2EE application uses.

If the application uses container-managed sign-on and the EIS has no special sign-on requirements for recovery, then OC4J does not require recovery sign-on information.

Table 4-1 summarizes OC4J XA recovery scenarios.

Table 4-1 OC4J XA Recovery Scenarios

Sign-on Mode for Original Connection | Mode for Sign-on Credentials | XA Recovery Credentials
--- | --- | ---
Component-managed (application supplies connection credentials) | OC4J is not aware of, and does not store, the user name and password for signing on to the EIS. | XA recovery credentials are according to your configuration. (See the next section, "Configuring XA Recovery in OC4J".) If you do not provide XA recovery sign-on configuration, OC4J attempts to connect to the EIS without a user name or password. If this fails, then transaction recovery fails.
Container-managed | OC4J determines the user name and password for connecting to the EIS. Based on the user that is signed on to the application (the OC4J user), OC4J applies security mapping to allow that user to obtain the user name and password for the EIS. | Again, XA recovery credentials are according to your configuration. If you do not provide XA recovery sign-on information, OC4J retrieves OC4J user information, uses the security mapping mechanism to determine the user name and password for the EIS, then connects to the EIS.

Once connection is reestablished, an `XAResource` object is obtained from the connection and is used to complete recovery.

Notes: Also be aware of the following: For XA recovery sign-on, OC4J supports resource adapters that accept password credentials. Resource adapters expecting other types of credentials cannot participate in OC4J XA recovery. After an OC4J instance fails, do not change any configuration for container-managed sign-on before restarting. This includes any changes that would be reflected in `<security-config>` settings in the `oc4j-ra.xml` file. It also includes the logic of any principal mapping modules used to support container-managed sign-on. Transaction recovery does not apply to emulated XA resources.

### Configu ring XA Recovery in OC4J

To configure the XA recovery sign-on parameters for a connection factory, take the following steps in the Application Server Control Console:

1. In the Connection Factories tab accessed from the Resource Adapter Home page for the appropriate resource adapter, choose the JNDI location of the connection factory you want to configure.

2. In the Options tab of the resulting Edit Connection Factory page, you can do any of the following:

   - Add a new user name. After specifying the user name, you can specify a password directly or indirectly. For a direct password, choose "Password" and type the password itself. For an indirect password, choose "Indirect Password" and type a key (which might just be the user name, for example). OC4J uses the key to do a lookup in the User Manager (specifically, in the `jazn-data.xml` file).

   - Change an existing user name or password.

Table 4-2 documents the sign-on properties, noting equivalent XML elements in the `oc4j-ra.xml` file. These are subelements of `<password-credential>`, which is a subelement of `<xa-recovery-config>`, which is a subelement of `<connector-factory>`.

Also see the context-sensitive topic "Edit Connection Factory Options Page" in the Application Server Control online help.

Table 4-2 XA Recovery Properties

Application Server Control Property | Corresponding XML Entity | Description
--- | --- | ---
User | `<username>` | Desired user name for XA recovery sign-on through this connection factory.
Password | `<password>` | Password indicator for XA recovery sign-on through this connection factory. Either the password itself for a direct password, or a key for lookup in the User Manager for an indirect password.

## Understanding J2CA Connection Wrapping

OC4J provides J2CA connection wrapping, a form of lazy enlistment of connections, to ensure that connections are properly enlisted with transactions. Connection wrapping supports connection association.

### Connection Association

The J2EE Connector Architecture specifies an association of an application-level connection handle with a `ManagedConnection` (physical connection) instance. For each connection request, a connection handle is created from a `ManagedConnection` instance. The connection handle maintains an association with the underlying `ManagedConnection` instance.

When a J2EE component caches a connection handle across transaction boundaries, the container may need to reassociate the handle with a different physical connection to maintain transactional correctness. Without this re-association, it is possible that work done in one transaction could be mixed up with work done in different transaction.

The container uses connection association to ensure that the connection handle remains associated with a physical connection that is appropriate for the current transactional context and connection sharing scope. Through the `associateConnection` method of the `ManagedConnection` interface, the container can change the association of a connection handle with a managed connection instance. The `associateConnection` method dissociates the given connection handle from its associated `ManagedConnection` instance and reassociates the connection handle with itself.

A connection handle can be switched from one `ManagedConnection` instance to another. When a method is invoked on a connection handle, the container may need to transparently switch the handle to point to an appropriate shared `ManagedConnection` instance with the correct transaction scope. The J2EE Connector specification does not specify how a container determines that a transaction boundary has been crossed (when work is being done on a cached connection in a new transaction context).

Note: In most cases, switching `ManagedConnection` instances for connection handles used across transaction boundaries is required only if the connections are shareable. An application can indicate that the connections that it references are unshareable. A connection that is marked as unshareable can be referenced only by a single connection handle. This means that as long as connection handle for an unsharable connection is open, it can remain associated with the same ManagedConnection. This is true even if the connection handle is cached across transaction boundaries.

The J2CA lazy connection association optimization enables the J2CA container to reclaim hibernating `ManagedConnection` instances, which allows for a more optimal use of connection resources. This is achieved by allowing the JCA container to dissociate a connection handle from its associated `ManagedConnection` instance, leaving the handle in an inactive state and freeing the `ManagedConnection` instance for reuse. The next time the connection handle is used, it needs to be reassociated with an appropriate `ManagedConnection` instance. With lazy association, it is up to the resource adapter to notify the J2CA container when a connection handle needs to be re associated if the handle has been dissociated from its `ManagedConnection` instance.

Note: The lazy connection association is optional for the resource adapter.

### Transaction Enlistment

In most cases the connection association mechanism will ensure that a connection handle is associated with a `ManagedConnection` instance that is appropriate for the current transaction context. However, in some cases where a connection handle is used across a transaction boundary, connection reassociation is not appropriate, as in unsharable connections. In these cases, the J2CA container still needs to ensure that the currently associated `ManagedConnection` instance is enlisted in the current transaction context. As with connection association, the problem for the container is how to know that a transaction boundary has been crossed.

The J2CA lazy transaction enlistment optimization addresses this problem, since it is up to the resource adapter to notify the container that a connection should be enlisted in the transaction (if there is one). However, lazy transaction enlistment is optional. OC4J provides J2CA connection wrapping to ensure that connections are properly enlisted if a resource adapter does not support lazy enlistment.

### J2CA Connection Handle Wrapping

When an application component obtains a connection through a JC2A resource adapter, OC4J creates a wrapper object around the connection handle returned by the connection factory. The wrapper object is what is actually returned to the application. By wrapping connections supplied by the resource adapter, the container can intervene to ensure that the connection handle is associated with a physical connection that is appropriate for the current transactional context and connection sharing scope.

The connector connection wrapper classes implement the same interfaces as the resource adapter's connection handle. Each wrapper object is created with a reference to the actual connection handle object returned by the resource adapter. Every method call is intercepted in the wrapper before it is delegated to the underlying referenced connection handle.

For example, a call to some method on a connector connection wrapper would ÒinterceptÓ and ensure that the connection handle was associated with a managed connection that was properly enlisted with the current transaction context. This may involve reassociating the connection handle to a new managed connection or simply making sure that the currently associated managed connection is enlisted in the current transaction context. The connector connection wrapper would then delegate the method call to the underlying connection handle object.

### Connection Association Scenarios

The scenarios in this section illustrate some issues with using connection associations:

- Scenario 1: Enlistment of a Connection Obtained Outside a Transaction

- Scenario 2: Transactional Context Switch

- Scenario 3: Handles for a Shared Connection in Different Transactional Contexts

#### Scenario 1: Enlistment of a Connection Obtained Outside a Transaction

An application obtains a connection outside of a transaction and then use the connection in the scope of a transaction.

1. An application obtains a connection from J2CA.

2. The application begins a transaction using `UserTransaction.begin().`

3. The application uses another resource in the transaction that gets enlisted.

4. The application uses the J2CA connection in the scope of the transaction.

The J2CA connection would not be associated with the transaction because it was created outside of the scope of the transaction. This will result in a nonatomic transaction outcome in which the work that is enlisted in the transaction may roll back and the work done on the JCA connection could commit, or vice versa.

#### Scenario 2: Transactional Context Switch

An application obtains an emulated J2CA connection in the scope of a transaction so that the connection is enlisted and later used in another transactional context.

- An application starts a global transaction.

- The application calls a method on a stateful session bean with a required `tx` attribute. Because a transaction is already associated with the thread, the EJB container does not start a new transaction.

- An emulated JC2A connection is obtained in this method and used to alter some data. When created, the connection is enlisted with the transaction and cached by the instance (not closed).

- The method returns without committing the transaction because it was in place prior to the method invocation.

- The application calls a different method on the same stateful session bean with a `tx` attribute of `RequiresNew`. This forces the EJB container to suspend the existing transaction association and start a new transaction for the method invocation.

- The bean uses the same connection handle that was used in the previous method invocation.

At this point, because the connection handle is still using the same 1pc physical connection as it was for the first method invocation, which was in a different transactional scope, all work done in method invocation two on the emulated J2CA connection is done on behalf of the original, suspended transaction and not the new transaction used in method invocation two. The connection handle must recognize that the transactional context has changes and swap out the physical connection being used by the handle.

This scenario will lead to incorrect outcomes because the second transaction may result in a rollback where the first may commit. In an attempt to prevent an inconsistent outcome, J2CA currently throws an exception on suspension of the transactional context in which an emulated connection is enlisted. This would prevent OC4J users from performing the preceding legal scenario.

Note: This scenario is a problem only for emulated connections because XA connections would send the begin and end calls to the XA resource and the resource would associate or disassociate the connection from a transaction. With an emulated connection, OC4J cannot send these begin and end calls to the resource, so OC4J must keep an association of physical connections to transactional contexts and switch physical connections according to the transaction context in place for any given invocation.

#### Scenario 3: Handles for a Shared Connection in Different Transactional Contexts

Two connection handles pointing to the same physical connection due to connection sharing are later used in different transactional contexts. This scenario may use either emulated or nonemulated connections.

1. An application calls a method on EJB A with a `tx` attribute of `Required`. The EJB container starts a new transaction.

2. EJB A gets a connection to `resource1` and uses the connection in the scope of the transaction. The connection is therefore enlisted with the transaction. The connection is cached for later use.

3. EJB A calls a method on EJB B, which has a `tx` attribute of `Required`. Because a transaction is already associated with the thread, a new transaction is not created.

4. EJB B also gets a connection to `resource1` and caches the connection. Because of connection sharing, both EJB A's connection handle and EJB B's connection handle will point to the same physical connection.

5. Both method invocations complete successfully and the transaction commits. At this point the transaction has committed and both connection handles point to the same physical connection.

6. Later, the application calls a different method on EJB A with a `tx` attribute of `Required`. The EJB container starts a new transaction.

7. EJB A uses the previously cached connection in the scope of the newly created transaction.

   Note: Currently, the connection is not associated with the transaction as in Scenario 1. This scenario is assuming that the enlistment issue has been fixed and the connection is properly enlisted in the transaction.

8. At the same time that EJB A is handling the preceding method invocation, another application thread calls a method on EJB B with a `tx` attribute of `Never`. Because of the `tx` attribute `Never`, the method will be invoked in a null transactional context.

9. EJB B uses the previously cached connection while not participating in a transaction.

At this point, EJB A and EJB B are using two distinct connection handles that point to the same physical connection. The physical connection is enlisted in EJB A's transaction but is also being used by EJB B with no transactional association. Because the connection is enlisted in EJB A's transaction, all work done by EJB B on its connection handle becomes part of EJB A's transaction, which is obviously incorrect.

This case is different than Scenario 2 in that it is valid for both XA connections and emulated connections. Also, the mechanism described in Scenario 3, where an exception is thrown from an emulated connection when suspend occurs, will not work in preventing an incorrect outcome in this case.