JBoss.orgCommunity Documentation

Development Guide

Development reference guide for the JBoss Transactions suite of software

by Mark Little, Jonathan Halliday, Andrew Dinn, and Kevin Connor
edited by Misty Stanley-Jones

Abstract

Development reference guide for the JBoss Transactions suite of software


This manual uses several conventions to highlight certain words and phrases and draw attention to specific pieces of information.

In PDF and paper editions, this manual uses typefaces drawn from the Liberation Fonts set. The Liberation Fonts set is also used in HTML editions if the set is installed on your system. If not, alternative but equivalent typefaces are displayed. Note: Red Hat Enterprise Linux 5 and later includes the Liberation Fonts set by default.

Four typographic conventions are used to call attention to specific words and phrases. These conventions, and the circumstances they apply to, are as follows.

Mono-spaced Bold

Used to highlight system input, including shell commands, file names and paths. Also used to highlight keycaps and key combinations. For example:

The above includes a file name, a shell command and a keycap, all presented in mono-spaced bold and all distinguishable thanks to context.

Key combinations can be distinguished from keycaps by the hyphen connecting each part of a key combination. For example:

The first paragraph highlights the particular keycap to press. The second highlights two key combinations (each a set of three keycaps with each set pressed simultaneously).

If source code is discussed, class names, methods, functions, variable names and returned values mentioned within a paragraph will be presented as above, in mono-spaced bold. For example:

Proportional Bold

This denotes words or phrases encountered on a system, including application names; dialog box text; labeled buttons; check-box and radio button labels; menu titles and sub-menu titles. For example:

The above text includes application names; system-wide menu names and items; application-specific menu names; and buttons and text found within a GUI interface, all presented in proportional bold and all distinguishable by context.

Mono-spaced Bold Italic or Proportional Bold Italic

Whether mono-spaced bold or proportional bold, the addition of italics indicates replaceable or variable text. Italics denotes text you do not input literally or displayed text that changes depending on circumstance. For example:

Note the words in bold italics above — username, domain.name, file-system, package, version and release. Each word is a placeholder, either for text you enter when issuing a command or for text displayed by the system.

Aside from standard usage for presenting the title of a work, italics denotes the first use of a new and important term. For example:

A transaction is a unit of work that encapsulates multiple database actions such that that either all the encapsulated actions fail or all succeed.

Transactions ensure data integrity when an application interacts with multiple datasources.

The interfaces specified by the many transaction standards tend to be too low-level for most application programmers. Therefore, Sun Microsystems created the Java Transaction API (JTA), which specifies higher-level interfaces to assist in the development of distributed transactional applications.

Note, these interfaces are still low-level. You still need to implement state management and concurrency for transactional applications. The interfaces are also optimized for applications which require XA resource integration capabilities, rather than the more general resources which other transactional APIs allow.

With reference to JTA 1.1 ( http://www.oracle.com/technetwork/java/javaee/tech/jta-138684.html ), distributed transaction services typically involve a number of participants:

application server

provides the infrastructure required to support the application run-time environment which includes transaction state management, such as an EJB server.

transaction manager

provides the services and management functions required to support transaction demarcation, transactional resource management, synchronization, and transaction context propagation.

resource manager

Using a resource adapter , provides the application with access to resources. The resource manager participates in distributed transactions by implementing a transaction resource interface used by the transaction manager to communicate transaction association, transaction completion and recovery.

A resource adapter is used by an application server or client to connect to a Resource Manager. JDBC drivers which are used to connect to relational databases are examples of Resource Adapters.

communication resource manager

supports transaction context propagation and access to the transaction service for incoming and outgoing requests.

From the point of view of the transaction manager, the actual implementation of the transaction services does not need to be exposed. You only need to define high-level interfaces to allow transaction demarcation, resource enlistment, synchronization and recovery process to be driven from the users of the transaction services. The JTA is a high-level application interface that allows a transactional application to demarcate transaction boundaries, and also contains a mapping of the X/Open XA protocol.

Compatibility

the JTA support provided by JBoss Transactions is compliant with the 1.1 specification.

The TransactionManager interface allows the application server to control transaction boundaries on behalf of the application being managed.

To obtain a TransactionManager , invoke the static method com.arjuna.ats.jta.TransactionManager.transactionManager .

The TransactionManager maintains the transaction context association with threads as part of its internal data structure. A thread’s transaction context may be null or it may refer to a specific global transaction. Multiple threads may be associated with the same global transaction. As noted in Section 2.3, “UserTransaction” , nested transactions are not supported.

Each transaction context is encapsulated by a Transaction object, which can be used to perform operations which are specific to the target transaction, regardless of the calling thread’s transaction context.


In a multi-threaded environment, multiple threads may be active within the same transaction. If checked transaction semantics have been disabled, or the transaction times out, a transaction may terminated by a thread other than the one that created it. In this case, the creator usually needs to be notified. JBoss Transactions notifies the creator during operations commit or rollback by throwing exception IllegalStateException .

The JTA supports the concept of a thread temporarily suspending and resuming transactions in order to perform non-transactional work. Call the suspend method to temporarily suspend the current transaction that is associated with the calling thread. The thread then operates outside of the scope of the transaction. If the thread is not associated with any transaction, a null object reference is returned. Otherwise, a valid Transaction object is returned. Pass the Transaction object to the resume method to reinstate the transaction context.

The resume method associates the specified transaction context with the calling thread. If the transaction specified is not a valid transaction, , the thread is associated with no transaction. if resume is invoked when the calling thread is already associated with another transaction, the IllegalStateException exception is thrown.


Note

JBoss Transactions allows a suspended transaction to be resumed by a different thread. This feature is not required by JTA, but is an important feature.

When a transaction is suspended, the application server must ensure that the resources in use by the application are no longer registered with the suspended transaction. When a resource is de-listed this triggers the Transaction Manager to inform the resource manager to disassociate the transaction from the specified resource object. When the application’s transaction context is resumed, the application server must ensure that the resources in use by the application are again enlisted with the transaction. Enlisting a resource as a result of resuming a transaction triggers the Transaction Manager to inform the resource manager to re-associate the resource object with the resumed transaction.

Typically, an application server manages transactional resources, such as database connections, in conjunction with some resource adapter and optionally with connection pooling optimization. For an external transaction manager to coordinate transactional work performed by the resource managers, the application server must enlist and de-list the resources used in the transaction. These resources, called participants , are enlisted with the transaction so that they can be informed when the transaction terminates, by being driven through the two-phase commit protocol.

As stated previously, the JTA is much more closely integrated with the XA concept of resources than the arbitrary objects. For each resource the application is using, the application server invokes the enlistResource method with an XAResource object which identifies the resource in use.

The enlistment request causes the transaction manager to inform the resource manager to start associating the transaction with the work performed through the corresponding resource. The transaction manager passes the appropriate flag in its XAResource.start method call to the resource manager.

The delistResource method disassociates the specified resource from the transaction context in the target object. The application server invokes the method with the two parameters: the XAResource object that represents the resource, and a flag to indicate whether the operation is due to the transaction being suspended ( TMSUSPEND ), a portion of the work has failed ( TMFAIL ), or a normal resource release by the application ( TMSUCCESS ).

The de-list request causes the transaction manager to inform the resource manager to end the association of the transaction with the target XAResource . The flag value allows the application server to indicate whether it intends to come back to the same resource whereby the resource states must be kept intact. The transaction manager passes the appropriate flag value in its XAResource.end method call to the underlying resource manager.

Transaction synchronization allows the application server to be notified before and after the transaction completes. For each transaction started, the application server may optionally register a Synchronization call-back object to be invoked by the transaction manager, which will be one of the following:

beforeCompletion

Called before the start of the two-phase transaction complete process. This call is executed in the same transaction context of the caller who initiates the TransactionManager.commit or the call is executed with no transaction context if Transaction.commit is used.

afterCompletion

Called after the transaction completes. The status of the transaction is supplied in the parameter. This method is executed without a transaction context.

The javax.transaction.TransactionSynchronizationRegistry interface, added to the JTA API in version 1.1, provides for registering Synchronizations with special ordering behavior, and for storing key-value pairs in a per-transaction Map. Full details are available from the JTA 1.1 API specification and javadoc. Here we focus on implementation specific behavior.


Accessing the TransactionSynchronizationRegistry via JNDI

In application server environments, the standard JNDI name binding is java:comp/TransactionSynchronizationRegistry .

Ordering of interposed Synchronizations is relative to other local Synchronizations only. In cases where the transaction is distributed over multiple JVMs, global ordering is not guaranteed.

The per-transaction data storage provided by the TransactionSynchronizationRegistry methods getResource and putResource are non-persistent and thus not available in Transactions during crash recovery. When running integrated with an application server or other container, this storage may be used for system purposes. To avoid collisions, use an application-specific prefix on map keys, such as put(“myapp_”+key, value) . The behavior of the Map on Thread s that have status NO_TRANSACTION or where the transaction they are associated with has been rolled back by another Thread , such as in the case of a timeout, is undefined. A Transaction can be associated with multiple Thread s. For such cases the Map is synchronized to provide thread safety.

Some transaction specifications and systems define a generic resource which can be used to register arbitrary resources with a transaction, the JTA is much more XA-specific. Interface javax.transaction.xa.XAResource is a Java mapping of the XA interface. The XAResource interface defines the contract between a ResourceManager and a TransactionManager in a distributed transaction processing environment. A resource adapter for a ResourceManager implements the XAResource interface to support association of a top-level transaction to a resource such as a relational database.

The XAResource interface can be supported by any transactional resource adapter designed to be used in an environment where transactions are controlled by an external transaction manager, such a database management system. An application may access data through multiple database connections. Each database connection is associated with an XAResource object that serves as a proxy object to the underlying ResourceManager instance. The transaction manager obtains an XAResource for each ResourceManager participating in a top-level transaction. The start method associates the transaction with the resource, and the end method disassociates the transaction from the resource.

The ResourceManager associates the transaction with all work performed on its data between invocation of start and end methods. At transaction commit time, these transactional ResourceManagers are informed by the transaction manager to prepare, commit, or roll back the transaction according to the two-phase commit protocol.

For better Java integration, the XAResource differs from the standard XA interface in the following ways:

By default, whenever an XAResource object is registered with a JTA-compliant transaction service, there is no way to manipulate the order in which it is invoked during the two-phase commit protocol, with respect to other XAResource objects. JBoss Transactions, however, provides support for controlling the order via the two interfaces com.arjuna.ats.jta.resources.StartXAResource and com.arjuna.ats.jta.resources.EndXAResource. By inheriting your XAResource instance from either of these interfaces, you control whether an instance of your class is invoked first or last, respectively.

The ArjunaCore Development Guide discusses the Last Resource Commit optimization (LRCO), whereby a single resource that is only one-phase aware, and does not support the prepare phase, can be enlisted with a transaction that is manipulating two-phase aware participants. This optimization is also supported within the JBoss Transactions.

In order to use the LRCO, your XAResource implementation must extend the com.arjuna.ats.jta.resources.LastResourceCommitOptimisation marker interface. A marker interface is an interface which provides no methods. When enlisting the resource via method Transaction.enlistResource, JBoss Transactions ensures that only a single instance of this type of participant is used within each transaction. Your resource is driven last in the commit protocol, and no invocation of method prepare occurs.

By default an attempt to enlist more than one instance of a LastResourceCommitOptimisation class will fail and false will be returned from Transaction.enlistResource. This behavior can be overridden by setting the com.arjuna.ats.jta.allowMultipleLastResources to true. However, before doing so you should read the section on enlisting multiple one-phase aware resources.

One-phase commit is used to process a single one-phase aware resource, which does not conform to the two-phase commit protocol. You can still achieve an atomic outcome across resources, by using the LRCO, as explained earlier.

Multiple one-phase-aware resources may be enlisted in the same transaction. One example is when a legacy database runs within the same transaction as a legacy JMS implementation. In such a situation, you cannot achieve atomicity of transaction outcome across multiple resources, because none of them enter the prepare state. They commit or roll back immediately when instructed by the transaction coordinator, without knowledge of other resource states and without a way to undo if subsequent resources make a different choice. This can result in data corruption or heuristic outcomes.

You can approach these situations in two different ways:

If neither of these options is viable, JBoss Transactions support enlisting multiple one-phase aware resources within the same transaction, using LRCO, which is discussed in the ArjunaCore Development Guide in detail.

When the same transactional resource is used to interleave multiple transactions, the application server must ensure that only one transaction is enlisted with the resource at any given time. To initiate the transaction commit process, the transaction manager is allowed to use any of the resource objects connected to the same resource manager instance. The resource object used for the two-phase commit protocol does not need to have been involved with the transaction being completed.

The resource adapter must be able to handle multiple threads invoking the XAResource methods concurrently for transaction commit processing. This is illustrated in Example 3.1, “Resource sharing example”.


You can associate timeout values with transactions in order to control their lifetimes. If the timeout value elapses before a transaction terminates, by committing or rolling back, the transaction system rolls it back. The XAResource interface supports a setTransactionTimeout operation, which allows the timeout associated with the current transaction to be propagated to the resource manager and if supported, overrides any default timeout associated with the resource manager. Overriding the timeout can be useful when long-running transactions may have lifetimes that would exceed the default, and using the default timeout would cause the resource manager to roll back before the transaction terminates, and cause the transaction to roll back as well.

If You do not explicitly set a timeout value for a transaction, or you use a value of 0, an implementation-specific default value may be used. In JBoss Transactions, property value CoordinatorEnvironmentBean.defaultTimeout represents this implementation-specific default, in seconds. The default value is 60 seconds. A value of 0 disables default transaction timeouts.

Unfortunately, imposing the same timeout as the transaction on a resource manager is not always appropriate. One example is that your business rules may require you to have control over the lifetimes on resource managers without allowing that control to be passed to some external entity. JBoss Transactions supports an all-or-nothing approach to whether or not method setTransactionTimeout is called on XAResource instances.

If the JTAEnvironmentBean.xaTransactionTimeoutEnabled property is set to true, which is the default, it is called on all instances. Otherwise, use the setXATransactionTimeoutEnabled method of com.arjuna.ats.jta.common.Configuration.

Atomic actions (transactions) can be used by both application programmers and class developers. Thus entire operations (or parts of operations) can be made atomic as required by the semantics of a particular operation. This chapter will describe some of the more subtle issues involved with using transactions in general and TxCore in particular.

In a multi-threaded application, multiple threads may be associated with a transaction during its lifetime, sharing the context. In addition, it is possible that if one thread terminates a transaction, other threads may still be active within it. In a distributed environment, it can be difficult to guarantee that all threads have finished with a transaction when it is terminated. By default, TxCore will issue a warning if a thread terminates a transaction when other threads are still active within it. However, it will allow the transaction termination to continue.

Other solutions to this problem are possible. One example would be to block the thread which is terminating the transaction until all other threads have disassociated themselves from the transaction context. Therefore, TxCore provides the com.arjuna.ats.arjuna.coordinator.CheckedAction class, which allows the thread or transaction termination policy to be overridden. Each transaction has an instance of this class associated with it, and application programmers can provide their own implementations on a per transaction basis.


When a thread attempts to terminate the transaction and there are active threads within it, the system will invoke the check method on the transaction’s CheckedAction object. The parameters to the check method are:

isCommit

Indicates whether the transaction is in the process of committing or rolling back.

actUid

The transaction identifier.

list

A list of all of the threads currently marked as active within this transaction.

When check returns, the transaction termination will continue. Obviously the state of the transaction at this point may be different from that when check was called, e.g., the transaction may subsequently have been committed.

A CheckedAction instance is created for each transaction. As mentioned above, the default implementation simply issues warnings in the presence of multiple threads active on the transaction when it is terminated. However, a different instance can be provided to each transaction in one of the following ways:

  • Use the setCheckedAction method on the BasicAction instance.

  • Define an implementation of the CheckedActionFactory interface, which has a single method getCheckedAction ( final Uid txId , final String actionType ) that returns a CheckedAction . The factory class name can then be provided to the Transaction Service at runtime by setting the CoordinatorEnvironmentBean.checkedActionFactory property.

By default, the Transaction Service does not maintain any history information about transactions. However, by setting the CoordinatorEnvironmentBean.enableStatistics property variable to YES , the transaction service will maintain information about the number of transactions created, and their outcomes. This information can be obtained during the execution of a transactional application via the com.arjuna.ats.arjuna.coordinator.TxStats class.

Example 4.2.  Class TxStats

public class TxStats

{
    /**
     * @return the number of transactions (top-level and nested) created so far.
     */
    public static int numberOfTransactions();
    /**
     * @return the number of nested (sub) transactions created so far.
     *
     public static int numberOfNestedTransactions();
     /**
     * @return the number of transactions which have terminated with heuristic
     *         outcomes.
     */
    public static int numberOfHeuristics();
    /**
     * @return the number of committed transactions.
     */
    public static int numberOfCommittedTransactions();
    /**
     * @return the total number of transactions which have rolled back.
     */
    public static int numberOfAbortedTransactions();  
    /**
     * @return total number of inflight (active) transactions.
     */  
    public static int numberOfInflightTransactions ();
    /**
     * @return total number of transactions rolled back due to timeout.
     */  
    public static int numberOfTimedOutTransactions ();
    /**
     * @return the number of transactions rolled back by the application.
     */  
    public static int numberOfApplicationRollbacks ();
    /**
     * @return number of transactions rolled back by participants.
     */  
    public static int numberOfResourceRollbacks ();
    /**
     * Print the current information.
     */  
    public static void printStatus(java.io.PrintWriter pw);
}

The class ActionManager gives further information about specific active transactions through the classes getTimeAdded , which returns the time (in milliseconds) when the transaction was created, and inflightTransactions , which returns the list of currently active transactions.

JBoss Transactions supports a number of different transaction log implementations. They are outlined below.

This chapter explains how to start and use the tools framework and what tools are available.

There are currently two command-line editors for manipulating the ObjectStore. These tools are used to manipulate the lists of heuristic participants maintained by a transaction log. They allow a heuristic participant to be moved from that list back to the list of prepared participants so that transaction recovery may attempt to resolve them automatically.

Each module of the system contains a modulepropertyManager class., which provides static getter methods for one or more nameEnvironmentBean classes. An example is com.arjuna.ats.arjuna.commmon.arjPropertyManager. These environment beans are standard JavaBean containing properties for each configuration option in the system. Typical usage is of the form:

int defaultTimeout = 

    arjPropertyManager.getCoordinatorEnvironmentBean().getDefaultTimeout();

These beans are singletons, instantiated upon first access, using the following algorithm.

Procedure 6.1. Algorithm for environment bean instantiation

  1. The properties are loaded and populated from a properties file named and located as follows:

    1. If the properties file name property is set (com.arjuna.ats.arjuna.common.propertiesFile), its value is used as the file name.

    2. If not, the default file name is used.

  2. The file thus named is searched for by, in order

    1. absolute path

    2. user.dir

    3. user.home

    4. java.home

    5. directories contained on the classpath

    6. a default file embedded in the product .jar file.

  3. The file is treated as being of standard java.util.Properties xml format and loaded accordingly. The entry names are of the form EnvironmentBeanClass.propertyName: <entry key="CoordinatorEnvironmentBean.commitOnePhase">YES</entry> or EnvironmentBeanClass.<storeType>propertyName: <entry key="ObjectStoreEnvironmentBean.communicationStore.objectStoreType">com.arjuna.ats.internal.arjuna.objectstore.VolatileStore</entry> The second form is required if you want to set properties on configuration beans other that the default bean instances. Valid values for Boolean properties are case-insensitive, and may be one of:

    • NO

    • YES

    • FALSE

    • TRUE

    • OFF

    • ON

    In the case of properties that take multiple values, they are white-space-delimited.


  4. After the file is loaded, it is cached and is not re-read until the JVM is restarted. Changes to the properties file require a restart in order to take effect.

  5. After the properties are loaded, the EnvironmentBean is then inspected and, for each field, if the properties contains a matching key in the search order as follows, the setter method for that field is invoked with the value from the properties, or the system properties if different.

  6. The bean is then returned to the caller, which may further override values by calling setter methods.

The implementation reads most bean properties only once, as the consuming component or class is instantiated. This usually happens the first time a transaction is run. As a result, calling setter methods to change the value of bean properties while the system is running typically has no effect, unless it is done prior to any use of the transaction system. Altered bean properties are not persisted back to the properties file.

You can configure the system using a bean wiring system such as JBoss Microcontainer or Spring. Take care when instantiating beans, to obtain the singleton via the static getter (factory) method on the module property manager. Using a new bean instantiated with the default constructor is ineffective, since it is not possible to pass this configured bean back to the property management system.

The transaction manager can generate a lot of logging information when configured to log in trace level. Here is a list of some of the log messages to check for.

The following table

Transaction Begin

When a transaction begins the following code is executed:

com.arjuna.ats.arjuna.coordinator.BasicAction::Begin:1342

tsLogger.logger.trace("BasicAction::Begin() for action-id "+ get_uid());

Transaction Commit

When a transaction commits the following code is executed:

com.arjuna.ats.arjuna.coordinator.BasicAction::End:1342

tsLogger.logger.trace("BasicAction::End() for action-id "+ get_uid());

Transaction Rollback

When a transaction commits the following code is executed:

com.arjuna.ats.arjuna.coordinator.BasicAction::Abort:1575

tsLogger.logger.trace("BasicAction::Abort() for action-id "+ get_uid());

Transaction Timeout

When a transaction times out the following code is executed:

com.arjuna.ats.arjuna.coordinator.TransactionReaper::doCancellations:349

tsLogger.logger.trace("Reaper Worker " + Thread.currentThread() + " attempting to cancel " + e._control.get_uid());

You will then see the same thread rolling back the transaction as shown above

Revision History
Revision 1Thu Oct 28 2010Misty Stanley-Jones
Initial conversion of book into Docbook
Revision 2Thu Apr 14 2011Tom Jenkinson
Taken from JBossJTA development guide and selected others