Skip Headers
Oracle® Containers for J2EE Services Guide
10g (10.1.3.1.0)

Part Number B28958-01
Go to Documentation Home
Home
Go to Book List
Book List
Go to Table of Contents
Contents
Go to Index
Index
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
View PDF

3 OC4J Transaction Support

This chapter discusses Transaction Support in Oracle Containers for J2EE (OC4J). It contains the following topics:

Transaction Management Tasks

This chapter describes the following transaction management tasks:

Configuring a Transaction Coordinator

In-Database Transaction Coordinator Considerations

Managing Transaction Demarcation. See Demarcating Transactions

Manual Commit and Rollback Operations

Monitoring the OC4J Transaction Manager

What's New

The following OC4J Transaction Support features and behaviors are new for this release:

Before Using OC4J in Production

Before using OC4J in production, Oracle recommends that the following tasks be performed:

Additional Documentation

The How-To documents at the following site provide information about OC4J features, including feature overviews and code excerpts relevant to the feature.

http://www.oracle.com/technology/tech/java/oc4j/1013/how_to/index.html

Introduction to OC4J Transaction Support

The Java Transaction API (JTA) is a specification developed by Sun Microsystems to provide support for global (distributed) transactions in the J2EE environment. Global transactions combine multiple enterprise systems - such as databases and message queues - into a single unit of work.

The JTA maps the specifications based on the Open Group Distributed Transaction Processing model into the Java environment. The Open Group XA specification defines the interface between transaction managers and resource managers. The JTA specification defines the interface between applications and transaction managers.

The JTA specification is available at http://java.sun.com/products/jta

What Is a Transaction?

A transaction is a mechanism that ensures correct outcomes in a system undergoing state changes. A transaction allows a programmer to scope a number of state changes in a system into a single unit of work. JTA transactions consist of enlisting resources and demarcating transactions. The changes that are scoped by the transaction may be either committed or rolled back.

Typically, a transaction is started by an application, the application performs some work against shared resources (such as one or more database systems), and the application commits the transaction. In the case of container-managed transactions, the application server starts the transaction.

For more about transaction processing in J2EE, you can refer to the following book:

Little, Maron, Pavlik: Java Transaction Processing: Design and Implementation, Prentice Hall, 2004

ACID

The transaction model that is supported by J2EE and most major information management systems are usually designed to preserve the ACID properties:

Note that the system infrastructure itself cannot maintain all of these properties. The consistency property requires that the application logic make valid changes to the system. For example, a transaction whose logic inserts an identifier representing a planet instead of a person into a human resource management database would create an inconsistent outcome - though the application server and database may have no way of knowing that the planet name was a meaningless value.

Note also that ACID guarantees place a burden on infrastructure and applications. If you need to reduce the overhead of ACID, design the work to use only one local resource, if possible, and not to use two-phase commit.

Middle-Tier Two-Phase Commit (2PC) Coordinator

In this release, transaction coordination functionality is now located in OC4J, replacing in-database coordination, which is now deprecated. Also, the middle-tier coordinator is now "heterogeneous", meaning that it supports all XA-compatible resources, not just those from Oracle.

The middle tier coordinator provides the following features:

Figure 3-1, "New Middle-Tier Coordinator Versus Deprecated In-Database Coordinator" shows the differences between the new middle tier coordinator and the deprecated in-database coordinator.

Figure 3-1 New Middle-Tier Coordinator Versus Deprecated In-Database Coordinator

Shows the new middle tier coordinator

Local and Global Transactions

The complexity of a transaction is determined by how many resources the application enlists within the transaction.

A local transaction involves only one resource and the transaction activity is scoped and coordinated locally to the resource itself. A local transaction uses the one-phase commit (1pc) protocol.

A global transaction (also called a distributed transaction) enlists more than one resource in the transaction. For example, a global transaction can be used to scope work on two databases. Transaction processing systems that support global transactions usually have several distinct logical components: a transaction factory, resource managers, coordinator and application. To achieve atomic outcomes in the global transaction, a termination protocol known as the two-phase commit (2pc) protocol is used.

The Two-Phase Commit Protocol

The two-phase commit (2pc) protocol is a mechanism to arrive at consensus among multiple participants in a global transaction. The protocol, as the name suggests, is divided into two phases. The first phase is often referred to as the voting phase. Each participant is asked to prepare the work in the transaction to be committed. If the participant is able to commit the work, it sends a message to the coordinator voting to commit.

During the voting, if ANY participant cannot prepare a transaction to commit, then all participants are instructed to roll back.

To guarantee the ACID properties, some transaction systems combine the two-phase commit protocol with the two-phase locking protocol. In practice, this means that no work may be performed in a transaction after the prepare phase has begun.

In order to provide atomic outcomes in the event of system failures, the two-phase commit protocol requires that the transaction manager log the transaction progress.

Using Multiple Resources

Resources are enlisted automatically by the application server when used within the scope of a transaction. However, to guarantee ACID properties in a two-phase commit transaction all participating resources must be XA compliant, with the exception of the last resource commit optimization.

Last Resource Commit

Last resource commit allows for a single non-XA-compliant resource to participate in an XA transaction. If more than one non-XA-compliant resource is enlisted in the transaction, then an exception is thrown from the enlistment attempt.

During the prepare phase, all XA- compliant resources are prepared. If all of the XA resources return OK from prepare, the coordinator performs a transfer of control to the non-XA compliant resource. If the non-XA compliant resource returns that it has committed, then the coordinator logs a commit decision, else a rollback decision is logged. The coordinator then notifies all of the XA resources of its decision.


Note:

Although this optimization works correctly a great majority of the time, there is some risk in using the last resource commit optimization. If a failure occurs during the transfer of control to the non-XA compliant resource, the coordinator has no way of knowing whether the resource committed or rolled back. This could lead to non-atomic outcomes, which would be very hard to rectify.

Because the last resource commit optimization only allows a single one-phase commit resource to be enlisted in a given transaction, OC4J restricts the enlistment of the one-phase commit resource to the root OC4J process. If an attempt is made to enlist a one-phase commit resource on a subordinate OC4J process, then an exception is thrown indicating that the server was unable to enlist the resource. This restriction is necessary because of the overhead involved in ensuring that only one one-phase commit resource was enlisted in a global transaction tree if subordinates were allowed to enlist one-phase commit resources when using the last resource commit optimization.


Notes:

  • It is possible to enlist more than one non-XA compliant resource in a global transaction if transaction logging is set to "none", however, there are no ACID guarantees nor recovery in this case. Setting transaction logging is described in "Configuring a Transaction Coordinator".

  • If the transaction manager is not using a persistent store, enlistment is allowed on the subordinate node.


To turn on last resource commit, enable transaction logging by configuring the transaction manager with a persistent store. The persistent store (and thereby logging) is disabled by default. See "Configuring a Transaction Coordinator".

In addition to allowing a single non-XA resource to participate in a global transaction, last resource commit can also be used as an optimization. By enlisting an XA-capable resource as a non-XA resource and using last resource commit, a gain in performance is achieved because the resource doesn't perform logging and a network call is eliminated because the coordinator would only make one call to the resource instead of two. Also, the resource would never be put in doubt, which would prevent resources from being locked. Although last resource commit can be used as a performance optimization, it is at the cost of guaranteed correctness.

Additional discussion of the last resource commit feature in OC4J can be found in the "Transaction Management" chapter of the Oracle Containers for J2EE Resource Adapter Administrator's Guide.

Resource Manager

A resource manager is responsible for managing shared resources. A common example of a resource manager is a relational database system.

Transaction Manager

A transaction manager combines the roles of transaction factory and coordinator. Applications communicate with the transaction manager to begin and end transactions and to enlist resources. When the application requests that a transaction be committed, the transaction manager will coordinate the two-phase commit protocol.

Heuristics

To achieve consensus, two-phase commit is a blocking protocol. This means that, if a coordinator fails before delivering the final phase messages, the participants must remain blocked, holding onto resources. Modern transaction systems add heuristics to two-phase commit, which allows such participants to make unilateral decisions about whether they will commit or rollback. If a participant makes a choice that turns out to be different from the one taken by other participants, then non-atomic behavior occurs. These decisions are generally made by administrative intervention. This is described in Manual Commit and Rollback Operations.

Synchronizations

Synchronizations are objects that are registered with a transaction and notified before and after running the two-phase commit protocol. For example, an application will often maintain it's own state and persist the cache to the resource only when necessary or just before completion and then release resources after completion.

Synchronizations are not available from the UserTransaction interface, so applications are not able to register synchronizations directly. This can only be done by the application server. In the case of CMP, the persistence layer handles this.

Information on EJBs is available in the Oracle Containers for J2EE Enterprise JavaBeans Developer's Guide.

Programming Models - Container-Managed and Bean-Managed Transactions

Enterprise Java Beans use JTA 1.0.1B for managing transactions through either container-managed transactions or bean-managed transactions.


Note:

Other terms for "container-managed transactions" are "declarative transactions" and "CMT".

Other terms for "bean-managed transactions" are "programmatic transactions" and "BMT".


Container-Managed Transactions

Container-managed transactions are controlled by the container. That is, the container either joins an existing transaction or starts a new transaction for the application—as defined within the deployment descriptor—and ends the newly created transaction when the bean method completes. It is not necessary for your implementation to provide code for managing the transaction.

Bean-Managed Transactions

Bean-managed transactions are programmatically demarcated within your bean implementation. The transaction boundaries are completely controlled by the application.

Demarcating Transactions

Demarcating a transaction means to initiate and terminate the transaction.

You can demarcate the transaction yourself by specifying that the bean is bean-managed transactional, or designate that the container should demarcate the transaction by specifying that the bean is container-managed transactional based on the transaction attributes specified in the EJB deployment descriptor.

Container-managed transaction is available to all EJBs. However, the bean-managed transactions are available for session beans and message-driven beans (MDBs) only. In other words, entity beans, designed for data access, must use container-managed transaction demarcation. Session beans can use either model.


Note:

Transactions cannot be demarcated from the application client container.

Specify the type of demarcation in the bean deployment descriptor. The following example shows a session bean that is declared as container-managed transactional by defining the <transaction-type> element as Container. To configure the bean for bean-managed transactional demarcation, define the <transaction-type> element as Bean.

Example: Session Bean Declared as Container-Managed Transactional

</session>
  <description>no description</description>
  <ejb-name>myEmployee</ejb-name>
  <home>cmtxn.ejb.EmployeeHome</home>
  <remote>cmtxn.ejb.Employee</remote>
  <ejb-class>cmtxn.ejb.EmployeeBean</ejb-class>
  <session-type>Stateful</session-type>
  <transaction-type>Container</transaction-type>
  <resource-ref>
   <res-ref-name>jdbc/OracleMappedDS</res-ref-name>
   <res-type>javax.sql.DataSource</res-type>
   <res-auth>Application</res-auth>
  </resource-ref>
</session>

Demarcating Container-Managed Transactions

If you define your bean to use container-managed transactions (CMTs), then you must specify how the container manages the JTA transaction for this bean in the <trans-attribute> element in the bean deployment descriptor as shown in the following example. The following table lists and describes the transaction attribute settings.

Table 3-1 <trans-attribute> Element Settings

Setting Description

NotSupported

The bean is not involved in a transaction.

If the bean invoker calls the bean while involved in a transaction, then the invoker's transaction is suspended, the bean executes, and when the bean returns, the invoker's transaction is resumed.

For message-driven beans (MDBs), this is the default.

Required

The bean must be involved in a transaction.

If the invoker is involved in a transaction, then the bean uses the invoker's transaction.

If the invoker is not involved in a transaction, then the container starts a new transaction for the bean. This is the default.

For CMP 2.0 entity beans, this is the default.

Supports

Whatever transactional state that the invoker is involved in is used for the bean.

If the invoker has begun a transaction, then the invoker's transaction context is used by the bean.

If the invoker is not involved in a transaction, then neither is the bean.

This is the default for all entity beans except CMP 2.0 entity beans and MDBs.

RequiresNew

Whether or not the invoker is involved in a transaction, this bean starts a new transaction that exists only for itself.

If the invoker calls while involved in a transaction, then the invoker's transaction is suspended until the bean completes.

Mandatory

The invoker must be involved in a transaction before invoking this bean. The bean uses the invoker's transaction context.

Never

The bean is not involved in a transaction. Furthermore, the invoker cannot be involved in a transaction when calling the bean.

If the invoker is involved in a transaction, then a RemoteException is thrown.



Note:

The default <trans-attribute> setting for each type of entity bean is as follows:
  • For CMP 2.0 entity beans, the default is Required.

  • For MDBs, the default is NotSupported

  • For all other entity beans, the default is Supports.


The following example shows the <container-transaction> portion of the EJB deployment descriptor. It demonstrates how this bean specifies the RequiresNew transaction attribute for all (*) methods of the myEmployee EJB.

Example: <container-transaction> in Deployment Descriptor

<assembly-descriptor>
      <container-transaction>
         <description>no description</description>
         <method>
            <ejb-name>myEmployee</ejb-name>
            <method-name>*</method-name>
         </method>
        <trans-attribute>RequiresNew</trans-attribute>
      </container-transaction>
   </assembly-descriptor>

No bean implementation is necessary to start, commit, or roll back the transaction. The container handles these functions based on the transaction attribute that is specified in the deployment descriptor.

Demarcating Bean-Managed Transactions

Web components (JSP, servlets) and stateless and stateful session beans can use programmatic transaction demarcation. Entity beans cannot, and thus must use container-managed transaction demarcation.


Note:

Client-side transaction demarcation is not supported in the application client container: OC4J does not support client-side transaction demarcation. This form of transaction demarcation is not required by the J2EE specification, and is not recommended for performance and latency reasons.

If you declare the bean as bean-managed transactional (BMT) within the <transaction-type> element of the bean deployment descriptor, then the bean implementation must demarcate the start, commit, or rollback for the global transaction.

For bean-managed (programmatic) transaction demarcation, the bean developer can use the UserTransaction interface to demarcate global transactions or RM-specific methods to demarcate RM local transactions.

The Web component or bean writer must explicitly issue the begin(), commit(), and rollback() methods of the UserTransaction interface, as shown in the following example:

Context initCtx = new Initial Context(); 
ut = (UserTransaction)  initCtx.lookup("java:comp/UserTransaction"); 

ut.begin(); 
// Do work. 
…
try {
    // Commit the transaction.
    ut.commit();
// Handle exceptions.  Should really catch specific exceptions, not Exception
} catch (Exception ex) { … }

Instead of creating an initial context, you can also use the @Resource annotation to request resource injection. In such scenarios, the lookup is done automatically at run-time. For example:

@Resource

begin(); // Do work. …try {    // Commit the transaction.

   commit();

// Handle exceptions. Should really catch specific exceptions, not Exception} catch (Exception ex) { … }

Configuring a Transaction Coordinator

This section discusses how to configure a 2PC transaction coordinator. The following topics are covered:

A transaction coordinator is configured using either the Oracle Enterprise Manager 10g Application Server Control Console or the transaction manager's configuration file (J2EE_HOME/config/transaction-manager.xml). This section primarily focuses on using the console.

Defining the Transaction Coordinator

A transaction coordinator can be defined using the Transaction Manager task or the JTAResource MBean. Both are accessed from the Administration tab in Application Server Control Console.

When configuring the Transaction Coordinator, a server restart is required for the changes to take effect. In addtion, all transactions must be purged before shutdown. If there are any transactions that are not purged, the server will wait until they have been administratively resolved. If the server shutdown is forced while transactions are still in doubt, the configuration change will not be saved.

Transaction Manager Task

To configure transaction coordinator using the Transaction Manager task:

  1. Log in to the Application Server Control Console and navigate to OC4J:Home > Administration> Task Name: Services>Transaction Manager (JTA): Go To Task.

  2. Click Administration.

  3. Complete the coordinator fields using Table 3-2 as a guide.

  4. Click Apply.

  5. Restart OC4J

JTAResource MBean

To configure the transaction coordinator using the JTAResource MBean:

  1. Log in to the Application Server Control Console and navigate to OC4J:Home > Administration> Task Name: JMX > System MBean Browser: Go To Task>JTAResource>oc4j-tm.

  2. Click Operations.

  3. From the list of operations, click configureCoordinator. The Operation screen displays.

  4. Complete the fields using Table 3-2 as a guide.

  5. Click Invoke Operation.

  6. Restart OC4J.

Table 3-2 Transaction Coordinator Parameters

Parameter Description

commitCoordinator

The two-phase commit coordinator type, either database or middle-tier.

The use of the in-database coordinator by OC4J is deprecated. Oracle recommends that the middle tier coordinator be used going forward. For additional information, see In-Database Transaction Coordinator Considerations.

logType

The log type, either none, file, or database. This setting applies only when commitCoordinator is set to middle-tier.

logLocation

The log location, either directory path for file or jndi location for database logging.

userName

The database username.

password

The database password.

retryCount

The number of times the coordinator will, when valid, retry commands to resource managers synchronously. Retries may occur, for example, if a resource manager returns XA_RETRY.


Setting Coordinator Attributes

The transaction coordinator contains several attributes that are used to control runtime performance. Changes to attributes take effect immediately and do not require a server restart.

General Attributes

The transaction coordinator contains two attributes that can be defined using either the Transaction Manager task or the JTAResource MBean. Table 3-3 describes the general attributes.

Table 3-3 General Attributes

Attribute Description

transactionTimeout

The default transaction timeout in seconds

maxConcurrentTransactions

The maximum number of concurrent transactions in the server before System Exceptions will be thrown. (-1 indicates unlimited.)


File Store Log Attributes

The file store log attributes are used to control the performance of the file store when using the transaction coordinator's file store logging. The attributes can only be modified using the JTAResource MBean or by manually editing the transaction-manager.xml file. Table 3-4 describes the file store log attributes.

Table 3-4 File store logging attributes

Attribute Description

minPoolSize

The number of files that are allocated to the pool during startup. Default is 40. Optimal value is enough to cover the maximum number of concurrent requests.

maxOpenFiles

The maximum number of file channels that can remain open/active. When this number is exceeded, the oldest channels will be released until the xid is requested again. Default is 256. Optimal value is enough to cover the maximum number of concurrent requests.

oldFileReleaseSize

The number of the oldest file handles that will be closed when max-open-files has been exceeded. Default is 20. Optimal value is a function of the odds of maxOpenFiles being exceeded, which should be avoided if at all possible or kept to a minimum otherwise.


Database Store Attributes

The database store log attributes are used to control the performance of the database store when using the transaction coordinator's database store logging. The attributes can only be modified using the JTAResource MBean or by manually editing the transaction-manager.xml file. Table 3-4 describes the file store log attributes.


Notes on Middle-tier Coordinator Database Logging:

  • The database must be Oracle.

  • The schema located at

    ORACLE_HOME/j2ee/home/database/j2ee/jta/oracle/2pc_jdbcstore.sql
    

    must be installed on the database.

  • The data source used for logging must be a native data source and not a managed data source.

  • The data source used for logging must be deployed to the default application.


Table 3-5 Database store logging attributes

Attribute Description

batchCreateInterval

The time in milliseconds between each batch write of transactions. Default is 10. Optimal value is small but relates to the cost of database call (such as network latency) and jvm heap size.

batchStateInterval

The time in milliseconds between each batch write of transaction state changes. Default is 10. Optimal value is small but relates to the cost of database call (such network latency) and jvm heap size

batchPurgeInterval

The time in milliseconds between each batch purge of completed transactions. Default is 100. Optimal value is large but relates to the cost of database call (such as network latency) and jvm heap size


Configuring Supporting Resources

The transaction coordinator may require addtional configuration of resources depneding on runtime settings.

Server

The J2EE_HOME/config/server.xml file must always contain the following element for the transaction manager to be configured:

<transaction-manager-config path="./transaction-manager.xml"/>


Note:

All transaction manager configuration, such as the transaction-timeout attribute, is contained in the transaction-manager.xml file and is no longer contained in the server.xml file.

For reference documentation of server.xml, see Oracle Containers for J2EE Configuration and Administration Guide Appendix B - Configuration Files Used in OC4J, Section - "Overview of the OC4J Server Configuration File (server.xml)".

Data Source

The J2EE_HOME/config/data-sources.xml file is used to specify recovery information necessary for data-sources to participate in 2pc transactions and recovery if the runtime user does not have XAResource.recover privileges.

//
<connection-pool
 name="cmt Connection Pool">
 min-connections="10"
 max-connections="30"
 inactivity-timeout="30"
 <connection-factory   factory-class="oracle.jdbc.xa.client.OracleXADataSource"
   user="scott"
   password="tiger"
   url="jdbc:oracle:thin:@localhost:1521:ORCL">

 <xa-recovery-config>
   <password-credential>
   <username>system</username>
   <password>manager</password>
   </password-credential>
 </xa-recovery-config>
 </connection-factory>
 </connection-pool>

<managed-data-source connection-pool-name="cmt Connection Pool"
           jndi-name="jdbc/cmt"
           name="cmt"/>


Note:

Data sources must be designated as managed data sources in order to participate in OC4J global transactions.

Resource Adapter

The oc4j-ra.xml file specifies XA and recovery information necessary for JMS or any other connectors to participate in 2pc transactions and recovery.

An XAConnectionFactory must be used in order to participate in two-phase commit processing and the connection-factory must define an xa-recovery-config element if the runtime user does not have permission to conduct the necessary XAResource.recover call.

For more information, see the "Transaction Management" chapter and the "OC4J Resource Adapter Configuration Files" appendix in the Oracle Containers for J2EE Resource Adapter Administrator's Guide.

The xa-recovery-config element takes the following form:

<connection-factory>
...
 <xa-recovery-config>
   <password-credential>
   <username>adapter_admin_user</username>
   <password>adapter_admin_pw</password>
   </password-credential>
 </xa-recovery-config>
...
 </connection-factory>

The following list shows examples of vendor-specific permissions. Those relating to RDBMS resource managers are specified in the data-sources.xml.

  • Oracle: select privileges on DBA_PENDING_TRANSACTIONS as well as execute privileges on sys.dbms system in version 9.2 and later of the RDBMS

  • DB2: sysadmin role

  • MSSQL: execute privileges on XA stored procedures

  • MQSeries: sysadmin role

In-Database Transaction Coordinator Considerations

This section discusses requirements for using the in-database two-phase commit coordinator.


Note:

The use of the in-database two-phase commit coordinator by OC4J is deprecated. Oracle recommends that the middle tier coordinator be used going forward.

You must configure the in-database two-phase commit engine with the following:

  • Fully-qualified database links from the coordinating database to each of the databases involved in the transaction. When the transaction ends, the two-phase commit engine communicates with the included databases over their fully-qualified database links.

  • A user that is designated to create sessions to each database involved and is given the responsibility of performing the commit or rollback. The user that performs the communication must be created on all involved databases and be given the appropriate privileges.


Note:

For in-database two-phase commit (2pc) functionality, use Oracle Database version 9.2.0.4 or later. The in-database two-phase commit (2pc) function is not available with Oracle Database version 9.2 or earlier.


Notes on In-Database Coordinator Configuration:

  • The database used must be Oracle.

  • The data source specified as the coordinator must be a native data source and not a managed data source.

  • The in-database coordinator cannot be used within propagated transactions (neither as the root nor interposed coordinator) and does not provide a last resource commit optimization]

  • The data source specified as the coordinator must be deployed to the default application.


Designate and configure an eligible Oracle database as the two-phase commit engine as follows:

  1. Define a managed data source in the JDBC Resources page of the Application Server Control Console or in the data-sources.xml file.

    The following example shows the definition in the data-sources.xml file.

    <connection-pool
          name="OracleCommitDS">
          min-connections="10"
          max-connections="30"
          inactivity-timeout="30"
          <connection-factory
              factory-class="oracle.jdbc.xa.client.OracleXADataSource"
              user="scott"
              password="tiger"
              url="jdbc:oracle:thin:@localhost:1521:ORCL">
          </connection-factory>
      </connection-pool> 
    <managed-data-source connection-pool-name="Example Connection Pool"
                             jndi-name="jdbc/OracleCommitDS"
                             name="OracleCommitDS"/>
    
    
    
  2. Refer to the two-phase commit engine DataSource in the transaction-manager.xml as follows:

    <database location="jdbc/OracleCommitDS">
               <identity user-name="COORDUSR" password="COORDPW"/>
           </database>
    
    

    The identity element is used only if it is necessary to override the user and password specified in the managed data source.

  3. Create a user and grant the appropriate permissions on all databases involved in the transaction.

    • Create the user on the two-phase commit engine that facilitates the transaction.

    • The user opens a session from the two-phase commit engine to each of the involved databases.

    • Grant the CONNECT, RESOURCE, CREATE SESSION privileges for the user to connect to each of these databases. The FORCE ANY TRANSACTION privilege allows the user to commit or roll back the transaction.

    For example, if the user that facilitates the transaction is COORDUSR, then the following example shows the operations on the two-phase commit engine and EACH database involved in the transaction:

    CONNECT SYSTEM/MANAGER;
    CREATE USER COORDUSR IDENTIFIED BY COORDUSR;
    GRANT CONNECT, RESOURCE, CREATE SESSION TO COORDUSR;
    GRANT FORCE ANY TRANSACTION TO COORDUSR;
    
    
  4. Configure fully-qualified public database links (using the CREATE PUBLIC DATABASE LINK command) from the two-phase commit engine to each database that is to be involved in the global transaction. These links are necessary for the two-phase commit engine to communicate with each database at the end of the transaction. These links enable the COORDUSR to connect to all participating databases.

  5. For each managed data source participating in the transaction, add the additional property of the fully-qualified-database link from the two-phase commit engine to this database.

    Add the property in the Connection Pool page of the Application Server Control Console or in the data-sources.xml file.

    The following example shows the definition in the data-sources.xml file.

    <connection-pool
          name="OracleDS1">
          min-connections="10"
          max-connections="30"
          inactivity-timeout="30"
          <connection-factory
              factory-class="oracle.jdbc.xa.client.OracleXADataSource"
              user="scott"
              password="tiger"
              url="jdbc:oracle:thin:@host1:1521:ORCL">
           <property name="dblink"
     value="DBLINK1.REGRESS.RDBMS.DEV.US.OLE.COM"/>
              </connection-factory>
      </connection-pool> 
    <managed-data-source connection-pool-name="Example Connection Pool"
                             jndi-name="jdbc/OracleDS1"
                             name="OracleDS1"/>
     <connection-pool
          name="OracleDS2">
          min-connections="10"
          max-connections="30"
          inactivity-timeout="30"
          <connection-factory
              factory-class="oracle.jdbc.xa.client.OracleXADataSource"
              user="scott"
              password="tiger"
              url="jdbc:oracle:thin:@host2:1521:ORCL">
           <property name="dblink"
     value="DBLINK2.REGRESS.RDBMS.DEV.US.OLE.COM"/>
          </connection-factory>
     </connection-pool> 
    <managed-data-source connection-pool-name="Example Connection Pool"
                             jndi-name="jdbc/OracleDS2"
                             name="OracleDS2"/>
    
    

Managing the OC4J Transaction Manager

This section discusses the following operations that can be performed during run time:

Manual Commit and Rollback Operations

Path to the JTAResource MBean:

OC4J:Home > Administration tab > Task Name: JMX > System MBean Browser: Go To Task

The following operations of the JTAResource MBean, which is accessible through the Application Server Control Console, can be used to force the outcome of a current transaction:

Operation Description
heuristicCommit Make an autonomous commit decision for an in-doubt transaction
heuristicRollback Make an autonomous rollback decision for an in-doubt transaction
setRollbackOnly Make an autonomous setRollbackOnly decision for an active transaction

Monitoring the OC4J Transaction Manager

This section discusses the following features, which are available through the JTAResource MBean:

OC4J Transaction Support Statistics

The statistics listed in the following table are provided by the JTAResource MBean, which is accessible through the Application Server Control Console.

Statistic Description
ActiveCount Total count of active transactions.

A consistently high value can indicate a heavy load on the server.

Suggest balancing across the cluster.

CommittedCount Total count of transactions that have committed.

This value can be used to determine the average load on the server since startup (or since the time the statistic was reset). Similar to activeCount, a high value for this average can indicate a heavy load on the server.

Suggest load balancing.

RolledbackCount Total count of transactions that have rolled back.

A high value might indicate an issue in the system (such as a database down) resulting in performance degradation.

Examine the fine-grained rollback cause counts and logs for the cause of the rollbacks.

RolledbackDueToTimedOutCount Total count of transactions that have rolled back due to timeout.

A high number might indicate any of several issues causing the transaction (or activity within transactional bounds) to time out. Possibly the timeout value specified is not flexible enough.

Determine what activities within the transactions involved (which may be of a certain type/application) are taking up time or adjust the transaction-timeout value in the transaction-manager.xml configuration file.

RolledbackDueToAppCount Total count of transactions that have rolled back due to the application calling setRollbackOnly or rollback explicitly.

A high value can occur for any reason, but will most often occur due to some handled exception within an application (such as SQLException during database update).

Examine application code that calls setRollbackOnly or rollback to see why it is doing so.

RolledbackDueToResourceCount Total count of transactions that have rolled back due to and error in an enlisted resource.

A high value might indicate an issue with one or more resource managers (such as database) or with the network connection between OC4J and these resources.

Examine the OC4J and resource manager logs.

RolledbackDueToAdminCount Total count of transactions that have rolled back due to administrative action.

A high value suggests that the system or application may not be automated enough (such as too much system administration in general or inadequate transaction architecture handling). Or possibly a particular issue has occurred that required extensive administration.

Analyze logs for trends and contact those responsible for the administrative action.

RollbackExceptionCount Total count of RollbackExceptions encountered.

A high value might indicate an issue in the system (such as a database down) resulting in performance degradation. This might be caused by a direct internal system failure or by the application calling setRollbackOnly for some reason.

Examine the fine-grained rollback cause counts and logs for the cause of the rollbacks and look into application code that calls setRollbackOnly.

HeuristicMixedExceptionCount Total count of HeuristicMixedExceptions encountered.

A high value might indicate a high number of potentially non-ACID outcomes resulting from inconsistent or inappropriate administrative intervention.

Analyze logs for trends and contact those responsible for the administrative action(s)

HeuristicRollbackExceptionCount Total count of Heuristic Rollback Exceptions encountered.

A high value suggests that the system or application might not be automated enough (such as too much system administration in general or inadequate transaction architecture handling). Or possibly an issue has occurred that required extensive administration. Unlike the rolledbackDueToAdminCount, which indicates administrative rollback at the root transaction manager level while a transaction is active, this count indicates either a subordinate Transaction Manager or resource manager being administratively rolled back while in the prepared state.

Analyze the OC4J and resource manager logs for trends and contact those responsible for the administrative action.

SecurityExceptionCount Total count of SecurityExceptions encountered.

A high value and most often any value greater than 0 might indicate an issue with the identity on the thread executing this.

Examine the OC4J logs.

IllegalStateExceptionCount Total count of IllegalStateExceptions encountered.

A high value here should be rare and only possible as a result of prior administrative intervention.

Analyze OC4J logs for trends and contact those responsible for the administrative action.

SystemExceptionCount Total count of SystemExceptions encountered.

A high value here should never occur and indicates a serious failure in the system.

Analyze OC4J and resource manager logs.

HeuristicCommittedCount Total count of heuristically committed transactions.

A high value suggests the system or application may not be automated enough (such as too much system administration in general or inadequate transaction architecture handling). Or possibly an issue has occurred that required extensive administration. This is due to a subordinate Transaction Manager and not a resource manager being administratively rolled back while in the prepared state.

Analyze OC4J logs for trends and contact those responsible for the administrative action.

HeuristicRolledbackCount Total count of heuristically rolled back transactions.

A high value suggests the system or application may not be automated enough (such as too much system administration in general or inadequate transaction architecture handling). Or possibly an issues has occurred that required extensive administration. This is due to a subordinate Transaction Manager and not a resource manager being administratively rolled back while in the prepared state.

Analyze OC4J logs for trends and contact those responsible for the administrative action.

HeuristicCount Total count of all heuristically rolled back and committed transactions.

See comments for heuristicCommittedCount and heuristicRolledbackCount.

AverageCommitTime Average commit time of all transactions.

This is the average of the performTransaction values. However, this is a mean average so there may be spikes in the system indicating other issues as well.

Analyze the finer-grain statistics as well as log files for indication of system spikes. Also analyze overall architecture as necessary.

PerformTransaction Time from beginning to end of the transaction.

This is useful as a high-level indicator of performance issues. However, since it is a measure from the beginning to the end of the transaction only, anything that occurs within this time frame might be the cause of a large value here. Some possibilities are: application logic, database activity, jms activity, transaction processing, and so on.

Analyze finer-grain statistics and overall architecture as necessary.

SinglePhaseCommitCompletion Time required for a single-phase commit completion.

A single-phase commit involves a single resource only and no 2PC costs (such as logging) are incurred. A large value here usually indicates an issue with the single resource being committed (such as network latency to the database).

Analyze the metrics of the resource involved in the commit.

TwoPhaseCommitCompletion Time required for a two-phase commit completion.

A high value indicates delays in the prepare and commit calls on resource managers or the transaction record logging in OC4J.

Analyze the metrics of the resources involved in and performance settings for transaction record logging in OC4J in the transaction-manager.xml file.

TransactionSuspended Time a transaction has been suspended.

A high value indicates that the transactions are being held in a suspended state waiting for a return call in a different or no transactional context (often from an EJB method call) or during propagation of a transaction context.

Analyze the application to determine what activity is taking place during the suspend or whether there is a network latency in the case of propagation.

RollbackCompletion Time required for a rollback completion.

A high value indicates delays in the rollback calls on resource managers which may be a result of network latency or resource manager issues.

Analyze the metrics of the resource(s) involved in the rollback.


The attributes listed in the following table are provided by the JTAResource MBean.

Attribute Description
inDoubtXids An array of in-doubt transaction Xids
activeXids An array of active transaction Xids
heuristicCommittedXids An array of heuristic committed transaction Xids
heuristicRolledbackXids An array of heuristic rolled back transaction Xids
currentTransactionDetail Details of all current transactions on the server, including those active, in-doubt, and recovering

The following JTAResource MBean operations are related to statistics.

Operation Description
clearStats Reset all OC4J Transaction Support statistics, except for activeCount, to 0
addThresholdEvent Add an event to be fired when the specified OC4J Transaction Count Statistic exceeds the specified threshold and again at the specified count intervals

addThresholdEvent takes the following parameters:

  • statName - The name of the Count Statistic to monitor

  • threshold1- The count at which to broadcast the event

  • repeatNotificationInterval - The interval count at which to broadcast subsequent events

removeThresholdEvent Remove a threshold event

removeThresholdEvent takes the following parameter:

  • statName - The name of the Count Statistic whose threshold event is to be removed


Subscribing to Event Notifications

The JTAResource MBean provides a set of event notifications that are listed on the MBean's Notifications tab. The tab is also used to subscribe to the notifications.

Notification Description
jtaThresholdEvent Notifies a listener when the count of a given JTA statistic exceeds a certain threshold and again at the specified count intervals.

To set the threshold, use the addThresholdEvent operation described in the preceding table.

jtaAbandonRecoveryEvent Notifies a listener when recovery of one or more transactions has been abandoned by an adminstrative action.
jtaSevereMessageEvent Notifies a listener when a severe level JTA messages has been logged.
jtaProtocolErrorEvent Notifies a listener when a ProtocolError has been thrown due to a protocol violation during two-phase commit processing

In addition, you can subscribe to notifications on the Notification Subscriptions page of the Application Server Control Console.

Path to the Global Notification Subscriptions Page:

OC4J:Home > Administration tab > Task Name: JMX > Notification Subscriptions

Notifications are viewed on the Notifications Received page of the Application Server Control Console.

Path to the Global Notifications Received Page:

OC4J:Home > Administration tab > Task Name: JMX > Notification Received

Managing OC4J Transaction Manager Recovery

In the normal case, for example where either OC4J or a resource participating in a 2PC transaction crashes and is subsequently brought back up, recovery occurs automatically, assuming proper configuration.

Recovery Management

The Application Server Control Console JTAResource MBean enables you to manage transaction recovery, including defining recovery abandonment rules and immediately abandoning a recovering transaction.

You can use the following operations of the JTAResource MBean to manage transaction recovery:

Operation Description
abandonRecovery Abandon recovery of the specfied transaction.
abandonRecoveryForType Abandon recovery of all transaction's of this type (application).
addThresholdEvent Add an event notification that is fired when the specified JTA stat count exceeds the specified threshold and again at the specified count intervals.
clearStats Reset all JTA aggregate count stats to 0.
configureCoordinator Configure the two-phase commit-coordinator (server restart is required for these settings to take effect).
configureDatabaseLoggingPerformance Configure the two-phase commit-coordinator database logging performance settings.
configureFileLoggingPerformance Configure the two-phase commit-coordinator file logging performance settings.
getMBeanInfo Get localized metadata for this MBean.
heuristicCommit Make an autonomous commit decision for an in-doubt transaction.
heuristicRollback Make an autonomous rollback decision for an in-doubt transaction.
removeThresholdEvent Remove a threshold event.
rollbackTransaction Make an autonomous rollback decision for an active transaction.
setAbandonRecoveryCountForResourceManager Add a recovery abandonment definition that specifies certain type (application) transactions will be abandoned if the specified participant (JNDI location) is the only resource in the transaction that has failed to recover in the given count of recovery re-attempts.
setAbandonRecoveryCountForType Add a recovery abandonment definition that specifies certain type (application) transactions will be abandoned if they have failed to recover in the given count of recovery re-attempts.
setAbandonRecoveryTimeForResourceManager Add a recovery abandonment definition that specifies certain type (application) transactions will be abandoned if the specified participant (JNDI location) is the only resource in the transaction that has failed to recover in the given time (seconds).
setAbandonRecoveryTimeForType Add a recovery abandonment definition that specifies certain type (application) transactions will be abandoned if they have failed to recover in the given time (seconds).
setRollbackOnly Make an autonomous setRollbackOnly decision for an active transaction.

Recovery Retry Interval

The recoveryRetryInterval attribute, also included with the JTAResource MBean, is used to indicate the amount of time in seconds that the recovery manager waits before re-attempting to recover transactions. The retry is subject to any abandonment definitions. The attribute is set to 300 seconds by default.

Logs

In the OPMN environment, if an OC4J instance crashes, then OPMN starts a new instance, which uses the crashed instance's logs.

In a standalone environment, if an OC4J instance crashes and cannot or should not be brought back for some reason, then the logs can be migrated to another OC4J instance.

Migrating the Logs in Standalone

The process for migrating logs depends on whether the instance is a root transaction manager, interposed transaction manager, or both and whether the file or database logging mechanism is used.

For a root transaction manager using the file store, you must either change the log location configuration of the new OC4J instances to the location of the crashed one or manually move the logs to the new OC4J instance log location. This must be done while the destination server is offline or shut down.

For an interposed transaction manager using the file store, the process is the same, however, any parent transaction managers of this interposed transaction manager must now update their references to this new location. This is possible using the -updateTransactionLogs offline admin command.

For a root transaction manager using the database store, the logs are migrated by updating the instance field of the oc4j_transaction table using the -updateTransactionLogs offline admin command. If the new OC4J instance is to use a completely new database, then the log file must be exported/imported as well.

For an interposed transaction manager using the database store, the process is the same, however, any parent transaction managers of this interposed transaction manager must now update their references to this new location. This is conducted using the -updateTransactionLogs offline admin command.

Two offline administrator commands are available through the admin.jar:

  • -analyzeTransactionLogs

  • -updateTransactionLogs


Note:

These notes apply to the context of standalone file migration, but they can be useful in certain situation in the opmn environment as well.

The -analyzeTransactionLogs command provides offline analysis of transaction log files. Do not use this utility if OC4J is running (use the Application Server Control Console instead). Arguments are:

Argument Description
-logType ["file" | "database"] The store type.
-location [location] The location of the store.

The directory for file logging.

The connection url for database logging.

-username [username] Applies only to database logging.
-password [password] Applies only to database logging.

The -updateTransactionLogs command provides offline updates of transaction log files. Do not use this utility if OC4J is running (use the Application Server Control Console instead). Arguments are:

Argument Description
-logType ["file" | "database"] The store type.
-location [location] The location of the store.

The directory for file logging.

The connection url for database logging.

-username [username] Applies only to database logging.
-password [password] Applies only to database logging.
-instanceId [old instance id] [new instanceid] The OC4J instance id associated with this log.
-branchLocation [old branch location] [new branch location] The location of the branch, generally the jndi location prefixed by the application name.
-branchArg [old branch arg] [new branch arg] The argument for the branch. For example, the container-managed sign-on username

Transaction Propagation between OC4J Processes over ORMI

Transaction context propagation makes it possible for multiple OC4J instances to participate in a single global transaction. Multiple OC4J instances need to participate in the same transaction if an OC4J instance makes a remote call into another OC4J instance in the scope of an existing transaction, assuming the EJB semantics for the method support scoping work in a client's transaction. An example of this is a servlet in OC4J instance:


Note:

Transaction context propagation and subject propagation is not supported for prior releases of OC4J.

When multiple OC4J instances participate in a single transaction, all work done by the participating OC4J instances as part of the global transaction is guaranteed to be atomic.

When a remote method invocation is made between OC4J instances, the requesting OC4J instance must create a transaction context that represents the current transaction and implicitly flow the context with the remote call over ORMI. This allows the OC4J instance that receives the remote method invocation to associate work done as part of the request with the transaction that is represented by the transaction context. The remote OC4J instance gets enlisted as a resource with the requesting OC4J instance, which creates a tree of OC4J instances in which the original OC4J instance is the root transaction coordinator and the child OC4J instances are nodes. It is possible for an OC4J instance to be both a parent and a child. In this case, the instance would act as a resource to its parent and as a coordinator to its children. This is called interpositioning. For more on ORMI, see Chapter 6, "Using Remote Method Invocation".

When the root coordinator commits the transaction, it runs the two-phase commit (2pc) protocol and sends completion calls to all of its registered resources, including enlisted OC4J instances. The root coordinator is responsible for driving transaction completion using the two-phase commit (2pc) protocol, while the subordinate OC4J instances merely act as resources in the transaction. It is possible that the root coordinator is not an OC4J instance but instead is an external coordinator as would be the case when OC4J imports a transaction using the J2CA 1.5 Transaction Inflow contract. When an OC4J instance is enlisted as a resource, it behaves like any other enlisted resource and is only responsible for preparing and committing its branch of the transaction. When an OC4J instance receives a call to prepare, it attempts to prepare all of its enlisted resources and returns the result. Likewise, when a commit call is received, the OC4J instance calls commit on all of its enlisted resources and returns the result to its parent.

For more information on the Transaction Inflow Contract, see the "Using RAs for Inbound Connections" chapter of the Oracle Containers for J2EE Resource Adapter Administrator's Guide.

By propagating transactions between OC4J instances over ORMI, transactions can span more than one OC4J instance.

The How-To document "How-To Propagate a transaction context between OC4J instances" and the ZIP file at the following site contains information and an example about transaction context propagation between OC4J instances:

http://www.oracle.com/technology/tech/java/oc4j/1013/how_to/how-to-transaction-propagation/doc/how-to-transaction-propagation.html

Configuring Transaction Propagation

This section describes transaction propagation configuration issues.

Enabling/Disabling


Note:

In most cases, transaction propagation is never disabled. Disabling transaction propagation is only done in exceptional circumstances such as troubleshooting. Exercise caution when disabling transaction propagation.

Transaction propagation is enabled by default in OC4J. To disable transaction propagation, set the system property -Drmi.disablePropagation=true. By setting this flag, all context propagation is disabled, which includes transaction and subject propagation. Enabling or disabling of transaction propagation affects all applications deployed to the server. Finer level granularity is not available. Great care should be taken when disabling transaction propagation. It is imperative that all OC4J processes that are involved in a request be configured identically in this regard. This means that all OC4J processes involved in a request must be enabled or that all of the OC4J processes must be disabled. If there is a mix of configurations, meaning that some OC4J processes in a request are enabled and that some are disabled, unexpected behavior may result. Also, if transaction propagation is disabled, then multiple OC4J processes cannot participate in a single global transaction. Only after fully understanding all of the consequences related to disabling transaction propagation should it be considered. Because of the possible adverse effects of disabling transaction propagation, it is recommended that this feature not be disabled.

Recovery

Because OC4J processes may act as transactional resources, they must be able to be recovered in the event of a failure. To facilitate transaction recovery, each OC4J process must have a configured password to be used by the transaction recovery manager at transaction recovery time. OC4J is shipped with a default password, which should be changed after install.

The recovery password is configured in the configuration file jazn-data.xml, which is in the $J2EE_HOME/config directory. To modify the transaction recovery password, change the credentials value for the user JtaAdmin in the jazn-data.xml file.

<user>
    <name>JtaAdmin</name>
    <display-name>JTA Recovery User</display-name>
    <description>Used to recover propagated OC4J transactions</description>
    <credentials>!newJtapassword</credentials>
</user>

Caution:

Even if OC4J is configured to use a security service other than JAZN, such as Oracle Internet Directory, the transaction recovery password must still be configured in jazn-data.xml.

During transaction recovery, the recovery password in the actual security store for the OC4J process that is being recovered must match the password that was configured in jazn-data.xml during transaction processing. If the password does not match, the recovery manager cannot contact the subordinate OC4J process and therefore the recovery manager cannot complete recovery.

Logging

Although transaction propagation does not require any additional transaction logging configuration, it is important to note that because a transaction my span multiple OC4J processes, each OC4J process must be configured independently with regards to logging.

Transaction Propagation Constraints

This section discusses the following constraints that apply to transaction propagation functionality:

Backwards Compatibility

Previous versions of OC4J do not support propagation. When an OC4J instance that supports transaction propagation makes a remote method invocation on a bean that is deployed on an older version of OC4J that does not support transaction propagation, no transaction context is propagated. For this reason, even though the caller may be in the scope of a transaction, the work done on the remote machine is not executed in the scope of the caller's transaction. The Application Deployer or Admin must understand the transactional requirements of an application prior to deployment if the application is to be deployed to various OC4J versions.

EJB Failover

When a transaction is propagated to an OC4J process, any failure that causes requests to that server to be failed over to a secondary server while in the scope of the propagated transaction will result in the transaction being rolled back.

EJB failover behavior is discussed in the Oracle Containers for J2EE Enterprise JavaBeans Developer's Guide.

Debugging and Troubleshooting

The following hints apply to debugging and troubleshooting: