Skip Headers
Oracle® Containers for J2EE Services Guide
10g Release 3 (10.1.3)
B14427-01
  Go To Documentation Library
Home
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index

Previous
Previous
Next
Next
 

5 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 the OC4J Transaction Manager

Configuring the In-Database Transaction Coordinator

Managing Transaction Demarcation. See Demarcating Transactions

Manual Commit and Rollback Operations

Monitoring the OC4J Transaction Manager

What's New in Transaction Support for OC4J 10.1.3

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 10g Release 3 (10.1.3) features, including feature overviews and code excerpts relevant to the feature.

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

5.1 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 5-1, "New Middle-Tier Coordinator vs. Deprecated In-Database Coordinator" shows the differences between the new middle tier coordinator and the deprecated in-database coordinator.

Figure 5-1 New Middle-Tier Coordinator vs. Deprecated In-Database Coordinator

Description of Figure 5-1  follows
Description of "Figure 5-1 New Middle-Tier Coordinator vs. Deprecated In-Database 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 "transaction-manager.xml".

  • 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 "transaction-manager.xml".

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 via 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.

5.2 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.

5.2.1 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>

5.2.2 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 5-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.

5.2.3 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) { … }

5.3 Configuring the OC4J Transaction Manager

This section discusses the following topics:

5.3.1 Configuring the Middle-Tier Transaction Manager in the Application Server Control Console and the JTA Resource MBean

The primary tool for configuring the Transaction Manager is the Oracle Enterprise Manager 10g Application Server Control Console. The Application Server Control Console is the preferred method for configuring OC4J.

Path to the Transaction Manager page in the Application Server Control Console:

OC4J:Home > Administration tab > Task Name: Services > Transaction Manager: Go To Task

From the Transaction Manager page:

  • The Performance tab presents OC4J Transaction Support statistics, as described in "Monitoring the OC4J Transaction Manager".

  • The Transactions tab presents the detail of all transactions that are currently running or being recovered and displays the details returned from the CurrentTransactionDetail attribute and allows for the administration of these transactions. The CurrentTransactionDetail attribute is available from the JTAResource MBean in the Application Server Control Console.

  • The Administration tab presents the current OC4J Transaction Support configuration and allows for it to be altered.

In addition to the Transaction Manager page, the JTAResource MBean, accessible through the Application Server Control Console, provides configuration and management services for OC4J Transaction Support.

Path to the JTAResource MBean:

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

The descriptions in the following tables refer to settings made on the Transaction Manager page, in the JTAResource MBean, and in the XML files. The XML files are discussed in "Configuring Middle-Tier OC4J Transaction Support in XML Files".

Table 5-2 JTAResource MBean configureCoordinator Operation 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 as of release 10.1.3. Oracle recommends that the middle tier coordinator be used going forward. For additional information, see Configuring the In-Database Transaction Coordinator.

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.



Coordinator Configuration Notes:

  • Server restart is required for coordinator configuration changes to take effect and 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 written to file.


Table 5-3 JTAResource MBean 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.)

transactionManagerConfigurationDetail

Details of the transaction manager configuration



Note:

Changes to the JTAResource MBean attributes are persisted to the transaction-manager.xml configuration file and take effect immediately. A server restart is not required.


5.3.2 Configuring Middle-Tier OC4J Transaction Support in XML Files

The following configuration files are used to configure OC4J Transaction Support:

5.3.2.1 server.xml

The server.xml file must simply contain the following element for the transaction manager to be configured:

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


Note:

As of 10.1.3, all transaction manager configuration, such as the transaction-timeout attribute, is now 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)".

5.3.2.2 transaction-manager.xml

The transaction-manager.xml file takes the following default form:

<?xml version="1.0" encoding="UTF-8"?>

<transaction-manager
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:noNamespaceSchemaLocation="http://xmlns.oracle.com/oracleas/schema/transaction-manager-10_0.xsd"
  transaction-timeout="30"
  max-concurrent-transactions="-1"
>
  <!-- transaction-timeout is in seconds and defaults to 30 -->
  <!-- a max-concurrent-transactions of -1 indicates unlimited concurrent transactions -->
  <commit-coordinator retry-count="4">
    <middle-tier>
      <!-- specify 'none' to turn off logging and increase performance, however,  note that recovery is impossible       -->
       <log type="none"/>

       <!-- specify 'file' to log to flat file (use the 'location' attribute to override the default directory and file-logging-performance attributes to override default settings)       <log type="file">
         <file-logging-performance min-pool-size="40" max-open-files="256" old-file-release-size="20" />
       </log>
       -->

       <!-- specify 'database' to log to the native-data-source specified by the 'location' attribute (use database-logging-performance attributes to override default settings
       <log type="database" location="jdbc/logging">
         <identity user="system" password="manager"/>
         <database-logging-performance batch-create-interval="10" batch-state-interval="10" batch-purge-interval="100" />       </log>
       -->

     </middle-tier>

     <!-- specify the following database element instead of the middle-tier when using the in-db coordinator
     <database location="jdbc/OracleDS">
       <identity user="system" password="manager"/>
     </database>
     -->

  </commit-coordinator>
</transaction-manager>


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.


5.3.2.2.1 Performance Settings

This section describes the performance settings for file store logging and for database store logging in the transaction-manager.xml file.

The following table lists and describes the settings for file store logging in the transaction-manager.xml file.

Table 5-4 File store logging attributes

Attribute Description

minPoolSize

The number of files that will be pre-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.


The following table lists and describes the settings for database store logging in the transaction-manager.xml file.

Table 5-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


5.3.2.3 oc4j-ra.xml

oc4j-ra.xml 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

5.3.2.4 data-sources.xml

The data-source.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.

5.3.3 Configuring the In-Database Transaction Coordinator

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 as of release 10.1.3. 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.

    For more on transaction-manager.xml, see "transaction-manager.xml".

  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"/>
    
    

5.4 Managing the OC4J Transaction Manager

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

5.4.1 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

5.4.2 Monitoring the OC4J Transaction Manager

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

5.4.2.1 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.

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

The following JTAResource MBean operations are related to statistics.

5.4.2.2 Event Notifications

You can add JMX event notifications that are fired when specified OC4J Transaction CountStatistics exceed given thresholds and again at the specified count intervals.

Use the following procedure to add a Threshold Event:

  1. Drill down to the JTAResource MBean.

  2. Select the addThresholdEvent operation and enter the following parameters:

    • statName - the name of a valid OC4J Transaction Count Statistic to monitor

    • threshold - the count at which to broadcast the event

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

To remove a threshold event, select the removeThreshold operation of the MBean and enter the name of the statistic as the argument.

You can subscribe to notification broadcasts on the Notification Subscriptions page of the Application Server Control Console.

Path to the Notification Subscriptions Page:

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

The notifications received can then be viewed on the Notifications Received page of the Application Server Control Console.

Path to the Notifications Received Page:

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

5.4.3 Managing OC4J Transaction Manager Recovery

Managing 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.

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. The process for doing so 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 admin commands are available via 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

5.5 Transaction Propagation between OC4J Processes over ORMI

This section discusses transaction propagation.

5.5.1 How Does Transaction Propagation Work?

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:

  • First, obtaining a reference to an EJB residing in OC4J instance.

  • Then, starting a transaction and making a method call on the remote EJB in the scope of the transaction.

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.


Note:

Transaction context propagation and subject propagation is supported between OC4J 10.1.3 instances only. These features are not supported between OC4J instances earlier than 10.1.3 or between an OC4J 10.1.3 instance and an earlier OC4J instance.

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 in OC4J".

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 via 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

5.5.2 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 OID, 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.

5.5.3 Transaction Propagation Constraints

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

5.5.3.1 Backwards Compatibility

OC4J 10.1.3 is the first version to support propagation, all previous versions did not. 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.

5.5.3.2 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.

5.6 Debugging and Troubleshooting

The following hints apply to debugging and troubleshooting: