Programmers Guide
Programmers Guide
3
Programmers Guide
JBTA-PG-4/4/07
JBTA-PG-4/4/07 i
Legal Notices
JBoss Inc. makes no warranty of any kind with regard to this material, including, but not limited to, the
implied warranties of merchantability and fitness for a particular purpose. JBoss Inc. shall not be liable for
errors contained herein or for incidental or consequential damages in connection with the furnishing,
performance, or use of this material.
Java™ and J2EE is a U.S. trademark of Sun Microsystems, Inc. Microsoft® and Windows NT® are
registered trademarks of Microsoft Corporation. Oracle® is a registered U.S. trademark and Oracle9™,
Oracle9 Server™ Oracle9 Enterprise Edition™ are trademarks of Oracle Corporation. Unix is used here
as a generic term covering all versions of the UNIX® operating system. UNIX is a registered trademark in
the United States and other countries, licensed exclusively through X/Open Company Limited.
Copyright
JBoss, Home of Professional Open Source Copyright 2006, JBoss Inc., and individual contributors as
indicated by the @authors tag. All rights reserved.
See the [Link] in the distribution for a full listing of individual contributors. This copyrighted
material is made available to anyone wishing to use, modify, copy, or redistribute it subject to the terms
and conditions of the GNU General Public License, v. 2.0. This program is distributed in the hope that it
will be useful, but WITHOUT A WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details. You should have received a copy of the GNU
General Public License, v. 2.0 along with this distribution; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA.
Software Version
Use, duplication, or disclosure is subject to restrictions as set forth in contract subdivision (c)(1)(ii) of the
Rights in Technical Data and Computer Software clause 52.227-FAR14.
Audience
This guide is most relevant to engineers who are responsible for administering JBoss
Transactions API 4.2.3 installations.
Prerequisites
Knowledge of JTA and JDBC.
Organization
This guide contains the following chapters:
ATA-PG-4/4/07 5
JBoss Transactions API 4.2.3Programmers Guide
Documentation Conventions
The following conventions are used in this guide:
Convention Description
Italic In paragraph text, italic identifies the titles of documents that are
being referenced. When used in conjunction with the Code text
described below, italics identify a variable that should be replaced
by the user with an actual value.
Bold Emphasizes items of particular importance.
Code Text that represents programming code.
Function | Function A path to a function or dialog box within an interface. For example,
“Select File | Open.” indicates that you should select the Open
function from the File menu.
( ) and | Parentheses enclose optional items in command syntax. The
vertical bar separates syntax items in a list of choices. For
example, any of the following three items can be entered in this
syntax:
Additional Documentation
In addition to this guide, the following guides are available in the JBoss Transactions API
4.2.3 documentation set:
6 JBTA-PG-04/04/07
About This Guide
Contacting Us
Questions or comments about JBoss Transactions API 4.2.3should be directed to our support
team.
JBTA-PG-4/4/07 7
Chapter 1
An introduction to the
JTA
The Java Transaction API
The interfaces specified by the many transaction standards are typically too low-level for
most application programmers. Therefore, Sun Microsystems has specified higher-level
interfaces to assist in the development of distributed transactional applications. Note, these
interfaces are still low-level, and require, for example, the programmer to be concerned with
state management and concurrency for transactional application. In addition, they are geared
more for applications which require XA resource integration capabilities, rather than the more
general resources which the other APIs allow.
From the transaction manager’s perspective, the actual implementation of the transaction
services does not need to be exposed; only high-level interfaces need to be defined 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
1
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.
ATA-PG-4/4/07 9
that allows a transactional application to demarcate transaction boundaries, and contains also
contains a mapping of the X/Open XA protocol.
Note: the JTA support provided by JBossJTA is compliant with the 1.0.1
specification.
10 JBTA-PG-04/04/07
Transactions
Chapter 2
Transactions
The API
The Java Transaction API consists of three elements: a high-level application transaction
demarcation interface, a high-level transaction manager interface intended for application
server, and a standard Java mapping of the X/Open XA protocol intended for transactional
resource manager. All of the JTA classes and interfaces occur within the
[Link] package, and the corresponding JBossJTA implementations within the
[Link] package.
Caution: Each Xid that JBossTS creates must have a unique node identifier
encoded within it and JBossTS will only recover transactions and states
that match a specified node identifier. The node identifier to use should
be provided to JBossTS via the
[Link] property. You must
make sure this value is unique across your JBossTS instances. If you do
not provide a value, then JBossTS will fabricate one and report the value
via the logging infrastructure. The contents of this should be
alphanumeric.
UserTransaction
The UserTransaction interface provides applications with the ability to control
transaction boundaries. It has methods for beginning, committing, and rolling back top-level
transactions: nested transactions are not supported, and begin throws the
NotSupportedException when the calling thread is already associated with a transaction.
UserTransaction automatically associates newly created transactions with the invoking
thread.
In order to select the local JTA implementation it is necessary to perform the following steps:
JBTA-PG-4/4/07 11
TransactionManager
The TransactionManager interface allows the application server to control transaction
boundaries on behalf of the application being managed.
The Transaction Manager maintains the transaction context association with threads as part of
its internal data structure. A thread’s transaction context is either null or it refers to a specific
global transaction. Multiple threads may be associated with the same global transaction. As
noted above, nested transactions are not supported.
The getTransaction method returns the Transaction object that represents the
transaction context currently associated with the calling thread. This object can be used to
perform various operations on the target transaction, described later.
The commit method is used to complete the transaction currently associated with the calling
thread. After it returns, the calling thread is associated with no transaction. If commit is
called when the thread is not associated with any transaction context, the TM throws an
exception. In some implementation, the commit operation is restricted to the transaction
originator only. If the calling thread is not allowed to commit the transaction, the TM throws
an exception. JBossJTA does not currently impose any restriction on the ability of threads to
terminate transactions.
The rollback method is used to rollback the transaction associated with the current thread.
After the rollback method completes, the thread is associated with no transaction.
12 JBTA-PG-04/04/07
Transactions
The resume method associates the specified transaction context with the calling thread. If
the transaction specified is a valid transaction, the transaction context is associated with the
calling thread; otherwise, the thread is associated with no transaction.
Note: if resume is invoked when the calling thread is already associated with
another transaction, the Transaction Manager throws the
IllegalStateException exception.
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.
The commit and rollback methods allow the target object to be committed or rolled
back. The calling thread is not required to have the same transaction associated with the
JBTA-PG-4/4/07 13
thread. If the calling thread is not allowed to commit the transaction, the transaction manager
throws an exception. At present JBossJTA does not impose restrictions on threads terminating
transactions.
Resource enlistment
Transactional resources such as database connections are typically managed by the
application server in conjunction with some resource adapter and optionally with connection
pooling optimization. In order for an external transaction manager to co-ordinate
transactional work performed by the resource managers, the application server must enlist
and de-list the resources used in the transaction. These resources (participants) are enlisted
with the transaction so that they can be informed when the transaction terminates, e.g., are
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 in-use by the application, the
application server invokes the enlistResource method with an XAResource object
which identifies the resource in use. See Chapter 4 for details on how the implementation of
the XAResource can affect recovery in the event of a failure.
The enlistment request results in the transaction manager informing the resource manager to
start associating the transaction with the work performed through the corresponding resource.
The transaction manager is responsible for passing the appropriate flag in its
[Link] method call to the resource manager.
The delistResource method is used to disassociate 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 results in the transaction manager informing 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 [Link] method call to the underlying resource manager.
Transaction synchronization
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:
14 JBTA-PG-04/04/07
Transactions
• The afterCompletion method is called after the transaction has completed. The
status of the transaction is supplied in the parameter. This method is executed
without a transaction context.
Transaction equality
The transaction manager implements the Transaction object’s equals method to allow
comparison between the target object and another Transaction object. The equals
method should return true if the target object and the parameter object both refer to the same
global transaction.
JBTA-PG-4/4/07 15
Chapter 3
The XAResource interface can be supported by any transactional resource adapter that is
intended to be used in an environment where transactions are controlled by an external
transaction manager, e.g., 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 resource manager
instance. The transaction manager obtains an XAResource for each resource manager
participating in a top-level transaction. It uses the start method to associate the transaction
with the resource, and it uses the end method to disassociate the transaction from the
resource.
The resource manager is responsible for associating the transaction with all work performed
on its data between the start and end invocations. At transaction commit time, these
transactional resource managers are informed by the transaction manager to prepare, commit,
or rollback the transaction according to the two-phase commit protocol.
In order to be better integrated with Java, the XAResource differs from the standard XA
interface in the following ways:
• The resource manager initialization is done implicitly by the resource adapter when
the resource (connection) is acquired. There is no xa_open equivalent.
• Rmid is not passed as an argument. Each Rmid is represented by a separate
XAResource object.
• Asynchronous operations are not supported because Java supports multi-threaded
processing and most databases do not support asynchronous operations.
• Error return values that are caused by the transaction manager’s improper handling
of the XAResource object are mapped to Java exceptions via the XAException
class.
• The DTP concept of “Thread of Control” maps to all Java threads that are given
access to the XAResource and Connection objects. For example, it is legal for
16 JBTA-PG-04/04/07
The Resource Manager
two different threads to perform the start and end operations on the same
XAResource object.
Note: Only one instance of each interface type may be registered with a specific
transaction.
In the TxCore manual we discussed the Last Resource Commit optimization (LRCO),
whereby a single resource that is only one-phase aware (does not support prepare), can be
enlisted with a transaction that is manipulating two-phase aware participants. This
optimization is also supported within the JTA aspects of JBossTS.
In order to use the LRCO, your XAResource implementation must extend the
[Link] marker
interface (it provides no methods). When enlisting the resource via
[Link], JBossTS will ensure that only a single instance of this
type of participant is used within each transaction. Your resource will be driven last in the
commit protocol: no invocation of prepare will occur.
JBTA-PG-4/4/07 17
However, there may be situations where multiple one-phase aware resources are enlisted
within the same transaction. For example, a legacy database running within the same
transaction as a legacy JMS implementation. In these situations it is not possible to achieve
atomicity of transaction outcome across multiple resources because none of them enter the
prepare (waiting for final outcome) state: they commit or rollback immediately when
instructed by the transaction coordinator, without knowledge of other resource states and
without any way of undoing should subsequent resources make a different choice. This can
result in data corruption or heuristic outcomes.
• Wrap the resources in compensating transactions. See the Web Services transactions
guides for further details.
• Migrate the legacy implementations to two-phase aware equivalents.
In the cases where neither of these options are viable, JBossTS does support the enlistment of
multiple one-phase aware resources within the same transaction. In order to do this, see the
section on the Last Resource Commit Optimization.
Caution: Even when this support is enabled, JBossTS will issue warnings when it
detects that the option has been enabled (“You have chosen to enable
multiple last resources in the transaction manager. This is transactionally
unsafe and should not be relied upon.”) and when multiple one-phase
resources are enlisted within the transaction (“This is transactionally
unsafe and should not be relied on.”).
• An XAResource object that allows the transaction manager to start and end the
transaction association with the resource in use and to coordinate transaction
completion process.
18 JBTA-PG-04/04/07
The Resource Manager
Once opened, the resource manager is kept open until the resource is released (closed)
explicitly. When the application invokes the connection’s close method, the resource
adapter invalidates the connection object reference that was held by the application and
notifies the application server about the close. The transaction manager should invoke the
[Link] method to disassociate the transaction from that connection.
The close notification allows the application server to perform any necessary cleanup work
and to mark the physical XA connection as free for reuse, if connection pooling is in place.
Threads of control
The X/Open XA interface specifies that the transaction association related xa calls must be
invoked from the same thread context. This thread-of-control requirement is not applicable to
the object-oriented component-based application run-time environment, in which application
threads are dispatched dynamically at method invocation time. Different threads may be
using the same connection resource to access the resource manager if the connection spans
multiple method invocation. Depending on the implementation of the application server,
different threads may be involved with the same XAResource object. The resource context
and the transaction context may be operated independent of thread context. This means that it
is possible for different threads to be invoking the start and end methods.
If the application server allows multiple threads to use a single XAResource object and the
associated connection to the resource manager, it is the responsibility of the application
server to ensure that there is only one transaction context associated with the resource at any
point of time. Thus the XAResource interface requires that the resource managers be able to
support the two-phase commit protocol from any thread context.
Transaction association
Transactions are associated with a transactional resource via the start method, and
disassociated from the resource via the end method. The resource adapter is responsible for
internally maintaining an association between the resource connection object and the
XAResource object. At any given time, a connection is associated with a single transaction,
or it is not associated with any transaction at all. Because JTA does not support nested
transactions it is an error for the start method to be invoked on a connection that is
currently associated with a different transaction.
Interleaving multiple transaction contexts using the same resource may be done by the
transaction manager as long as start and end are invoked properly for each transaction
context switch. Each time the resource is used with a different transaction, the method end
must be invoked for the previous transaction that was associated with the resource, and
start must be invoked for the current transaction context.
JBTA-PG-4/4/07 19
Externally controlled connections
For transactional application whose transaction states are managed by an application server,
its resources must also be managed by the application server so that transaction association is
performed properly. If an application is associated with a transaction, it is an error for the
application to perform transactional work through the connection without having the
connection’s resource object already associated with the global transaction. The application
server must ensure that the XAResource object in use is associated with the transaction.
This is done by invoking the [Link] method.
If a server side transactional application retains its database connection across multiple client
requests, the application server must ensure that before dispatching a client request to the
application thread, the resource is enlisted with the application’s current transaction context.
This implies that the application server manages the connection resource usage status across
multiple method invocations.
Resource sharing
When the same transactional resource is used to interleave multiple transactions, it is the
responsibility of the application server to 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. For example, with reference to the
code below, suppose we have a transactional resource r1. Global transaction xid1 was
started and ended with r1. Then a different global transaction xid2 is associated with r1. In
the meanwhile, the transaction manager may start the two phase commit process for xid1
using r1 or any other transactional resource connected to the same resource manager. The
resource adapter needs to allow the commit process to be executed while the resource is
currently associated with a different global transaction.
..
[Link](xid1); // disassociate xid1 to the connection
..
[Link](xid2); // associate xid2 to the connection
..
// While the connection is associated with xid2,
// the TM starts the commit process for xid1
status = [Link](xid1);
..
[Link](xid1, false);
20 JBTA-PG-04/04/07
The Resource Manager
• The local transaction must be committed (or rolled back) before starting a global
transaction in the connection.
• The global transaction must be disassociated from the connection before any local
transaction is started.
Transaction timeouts
Timeout values can be associated with transactions in order to control their lifetime. If a
transaction has not terminated (committed or rolled back) before the timeout value elapses,
the transaction system will automatically roll it back. The XAResource interface supports a
operation, which allows the timeout associated with the current transaction to be propagated
to the resource manager and if supported, will override any default timeout associated with
the resource manager. This can be useful when long running transactions may have lifetimes
that would exceed the default and in which case, if the timeout were not altered, the resource
manager would rollback before the transaction terminated and subsequently cause the
transaction to roll back as well.
Unfortunately there are situations where imposing the same timeout as the transaction on a
resource manager may not be appropriate. For example, if the system administrator wishes to
have control over the lifetimes on resource managers and does not want to (or cannot) allow
that control to be passed to some external entity. At present JBossTS supports an all-or-
nothing approach to whether or not setTransactionTimeout is called on XAResource
instances.
JBTA-PG-4/4/07 21
Dynamic Registration
Dynamic registration is not supported in XAResource because of the following reasons:
22 JBTA-PG-04/04/07
Transaction recovery
Chapter 4
Transaction recovery
Failure recovery
During recovery, the Transaction Manager needs to be able to communicate to all resource
managers that are in use by the applications in the system. For each resource manager, the
Transaction Manager uses the [Link] method to retrieve the list of
transactions that are currently in a prepared or heuristically completed state. Typically, the
system administrator configures all transactional resource factories that are used by the
applications deployed on the system. An example of such a resource factory is the JDBC
XADataSource object, which is a factory for the JDBC XAConnection objects.
Because XAResource objects are not persistent across system failures, the Transaction
Manager needs to have some way to acquire the XAResource objects that represent the
resource managers which might have participated in the transactions prior to the system
failure. For example, a Transaction Manager might, through the use of JNDI lookup
mechanism, acquire a connection from each of the transactional resource factories, and then
obtain the corresponding XAResource object for each connection. The Transaction Manager
then invokes the [Link] method to ask each resource manager to return the
transactions that are currently in a prepared or heuristically completed state.
If using the JBossJTA JDBC 2.0 driver, then JBossJTA will take care of all XAResource
crash recovery automatically. Otherwise one of the following recovery mechanisms will be
used:
• If the XAResource is serializable, then the serialized form will be saved during
transaction commitment, and used during recovery. It is assumed that the recreated
XAResource is valid and can be used to drive recovery on the associated database.
• The [Link],
[Link] and
[Link] interfaces are used.
These are documented in the JDBC chapters on failure recovery.
JBTA-PG-4/4/07 23
Note: In JBossTS 3.3 the interface XAConnectionRecovery was deprecated in
favor of XAResourceRecovery. Users are encouraged to move to his new
interface.
Recovering XAConnections
When recovering from failures, JBossJTA requires the ability to reconnect to databases that
were in use prior to the failures in order to resolve any outstanding transactions. Most
connection information will be saved by the transaction service during its normal execution,
and can be used during recovery to recreate the connection. However, it is possible that not
all such information will have been saved prior to a failure (for example, a failure occurs
before such information can be saved, but after the database connection is used). In order to
recreate those connections it is necessary to provide implementations of the following
JBossJTA interface [Link], one for
each database that may be used by an application.
Note: if using the transactional JDBC 2.0 driver provided with JBossJTA, then
no additional work is necessary in order to ensure that recovery occurs.
[Link]=[Link]
Additional information that will be passed to the instance when it is created may be specified
after a semicolon:
[Link]=[Link];my
Data=hello
Note: These properties need to go into the JTA section of the property file.
• initialise: once the instance has been created, any additional information which
occurred on the property value (anything found after the first semi-colon) will be
24 JBTA-PG-04/04/07
Transaction recovery
passed to the object. The object can then use this information in an implementation
specific manner to initialise itself, for example.
• hasMoreResources: each XAResourceRecovery implementation may provide
multiple XAResource instances. Before any call to getXAResource is made,
hasMoreResources is called to determine whether there are any further
connections to be obtained. If this returns false, getXAResource will not be called
again during this recovery sweep and the instance will not be used further until the
next recovery scan.
• getXAResource: returns an instance of the XAResource object. How this is created
(and how the parameters to its constructors are obtained) is up to the
XAResourceRecovery implementation. The parameters to the constructors of this
class should be similar to those used when creating the initial driver or data source,
and should obviously be sufficient to create new XAResources that can be used to
drive recovery.
<transaction-service>
<properties name="jdbc" type="system">
<property name="DatabaseURL"
value="jdbc:oracle:thin:@hostname:1521:sid"/>
<property name="UserName" value="username"/>
<property name="Password" value="password"/>
</properties>
</transaction-service>
<transaction-service>
<properties name="jdbc" type="system">
<property name="DatabaseJNDIName" value="java:ExampleDS"/>
<property name="UserName" value="username"/>
<property name="Password" value="password"/>
</properties>
JBTA-PG-4/4/07 25
</transaction-service>
26 JBTA-PG-04/04/07
JDBC and transactions
Chapter 5
The JDBC 2.0 support has been tested with the following drivers and databases:
However, these drivers and databases are no longer part of our supported platforms. They
may continue to work with JBossTS, but we cannot make that guarantee.
Managing transactions
JBossJTA must be able to associate work performed on a JDBC connection with a specific
transaction. Therefore, implicit transaction propagation and/or indirect transaction
management must be used by applications, i.e., for each JDBC connection it must be possible
for JBossJTA to determine the invoking thread’s current transaction context.
Restrictions
The following restrictions are imposed by limitations in the JDBC specifications and by
JBossJTA to ensure that transactional interactions with JDBC databases can be correctly
managed:
Nested transactions are not supported by JDBC 2.0. If an attempt is made to use a JDBC
connection within a subtransaction, JBossJTA will throw a suitable exception and no work
will be allowed on that connection. However, if you wish to have nested transactions, then
you can set the [Link] property to YES.
JBTA-PG-4/4/07 27
Transactional drivers
The JBossJTA approach to incorporating JDBC connections within transactions is to provide
transactional JDBC drivers through which all interactions occur. These drivers intercept all
invocations and ensure that they are registered with, and driven by, appropriate transactions.
There is a single type of transactional driver through which any JDBC driver can be driven;
obviously if the database is not transactional then ACID properties cannot be guaranteed.
This driver is [Link], which implements the
[Link] interface.
Loading drivers
The driver may be directly instantiated and used within an application. For example:
/*
* Register the driver via the system properties variable
* "[Link]"
*/
Properties p = [Link]();
switch (dbType)
{
case MYSQL:
[Link]("[Link]", "[Link]");
break;
case CLOUDSCAPE:
[Link]("[Link]", "[Link]");
break;
}
[Link](p);
Alternatively, the [Link]() method may be used to load the driver or drivers:
[Link]("[Link]");
Calling [Link]() will automatically register the driver with the JDBC driver
manager. It is also possible to explicitly create an instance of the JDBC driver:
[Link](drv);
When you have loaded a driver, it is available for making a connection with a DBMS.
28 JBTA-PG-04/04/07
JDBC and transactions
Connections
In this section we shall discuss the notion of transactional JDBC connections, how they are
managed within JBossJTA and the implications on using them within an application.
JDBC 2.0
Before describing the JDBC 2.0 support it is necessary to mention that the following
properties can be set and passed to the JBossJTA driver (they are all located in the
[Link] class):
• userName: the user name to use when attempting to connect to the database.
• password: the password to use when attempting to connect to the database.
• createDb: if set to true, the driver will attempt to create the database when it
connects. This may not be supported by all JDBC 2.0 implementations.
• dynamicClass: this specifies a class to instantiate to connect to the database, rather
than using JNDI.
XADataSources
JDBC 2.0 connections are created from appropriate DataSources. Those connections which
must participate within distributed transactions are obtained from XADataSources.
Therefore, when using a JDBC 2.0 driver, JBossJTA will use the appropriate DataSource
whenever a connection to the database is made. It will then obtain XAResources and register
them with the transaction via the JTA interfaces. It is these XAResources which the
transaction service will use when the transaction terminates in order to drive the database to
either commit or rollback the changes made via the JDBC connection.
There are two ways in which the JBossJTA JDBC 2.0 support can obtain XADataSources.
These will be explained in the following sections. Note, for simplicity we shall assume that
the JDBC 2.0 driver is instantiated directly by the application.
JBTA-PG-4/4/07 29
[Link]), the application is not tied at build time to only use a specific
(XA)DataSource implementation.
XADataSource ds = MyXADataSource();
Hashtable env = new Hashtable();
String initialCtx =
[Link]("Context.INITIAL_CONTEXT_FACTORY");
[Link](Context.INITIAL_CONTEXT_FACTORY, initialCtx);
[Link]("jdbc/foo", ds);
Then the application must pass an appropriate connection URL to the JDBC 2.0 driver:
[Link]([Link], "user");
[Link]([Link], "password");
The JNDI URL must be pre-pended with jdbc:arjuna: in order for the ArjunaJDBC2Driver
to recognise that the DataSource must participate within transactions and be driven
accordingly.
30 JBTA-PG-04/04/07
JDBC and transactions
The application code must specify which dynamic class the TransactionalDriver should
instantiate when setting up the connection:
[Link]([Link], "user");
[Link]([Link], "password");
[Link]([Link],
"[Link].sequelink_5_0");
JBossJTA connections can be used within multiple different transactions simultaneously, i.e.,
different threads, with different notions of the current transaction, may use the same JDBC
connection. JBossJTA does connection pooling for each transaction within the JDBC
connection. So, although multiple threads may use the same instance of the JDBC
connection, internally this may be using a different connection instance per transaction. With
the exception of close, all operations performed on the connection at the application level will
only be performed on this transaction-specific connection.
JBTA-PG-4/4/07 31
JBossJTA will automatically register the JDBC driver connection with the transaction via an
appropriate resource . When the transaction terminates, this resource will be responsible for
either committing or rolling back any changes made to the underlying database via
appropriate calls on the JDBC driver.
Once created, the driver and any connection can be used in the same way as any other JDBC
driver or connection.
try
{
[Link]("CREATE TABLE test_table (a INTEGER,b INTEGER)");
}
catch (SQLException e)
{
// table already exists
}
Connection pooling
For each user name and password, JBossJTA will maintain a single instance of each
connection for as long as that connection is in use. Subsequent requests for the same
connection will get a reference to the originally created connection, rather than a new
instance. Attempts to close the connection are allowed, but the connection will only actually
be closed when all users (including transactions) have either finished with the connection, or
issued close calls.
Reusing connections
Some JDBC drivers allow the reuse of a connection for multiple different transactions once a
given transaction has completed. Unfortunately this is not a common feature, and other
drivers require a new connection to be obtained for each new transaction. By default, the
JBossJTA transactional driver will always obtain a new connection for each new transaction.
However, if an existing connection is available and is currently unused, it is possible to make
JBossJTA reuse this connection. In order to do this, the reuseconnection=true option
must be specified on the JDBC URL. For example:
jdbc:arjuna:sequelink://host:port;databaseName=foo;reuseconnection=true
32 JBTA-PG-04/04/07
JDBC and transactions
AutoCommit
If AutoCommit of the [Link] is set to true for JDBC 1.0 then the
execution of every SQL statement is a separate top-level transaction, and grouping multiple
statements to be managed within a single OTS transaction is not possible. Therefore,
JBossJTA will disable AutoCommit on JDBC 1.0 connections before they can be used. If
auto commit is subsequently set to true by the application, JBossJTA will raise the
[Link].
Note: At present this property applies to all XA connections created in the JVM.
JBTA-PG-4/4/07 33
Chapter 6
Examples
JDBC example
The following code illustrates many of the points described above (note that for simplicity,
much error checking code has been remove). This example assumes that you are using the
transactional JDBC driver provided with JBossTS. For details about how to configure and use
this driver see the previous Chapter.
try
{
[Link]("\nCreating connection to database: "+url);
/*
* Create conn and conn2 so that they are bound to the JBossTS
* transactional JDBC driver. The details of how to do this will
* depend on your environment, the database you wish to use and
* whether or not you want to use the Direct or JNDI approach. See
* the appropriate chapter in the JTA Programmers Guide.
*/
try
{
[Link]("DROP TABLE test_table");
[Link]("DROP TABLE test_table2");
}
catch (Exception e)
{
// assume not in database.
}
try
{
[Link]("CREATE TABLE test_table (a INTEGER,b
INTEGER)");
[Link]("CREATE TABLE test_table2 (a INTEGER,b
INTEGER)");
}
catch (Exception e)
34 JBTA-PG-04/04/07
Examples
{
}
try
{
[Link]("Starting top-level transaction.");
[Link]().begin();
while ([Link]())
{
[Link]("Column 1: "+[Link](1));
[Link]("Column 2: "+[Link](2));
}
[Link]("\nNow attempting to rollback changes.");
[Link]().rollback();
[Link]().begin();
stmtx = [Link]();
ResultSet res2 = null;
stmtx = [Link]();
res2 = [Link]("SELECT * FROM test_table2");
while ([Link]())
{
[Link]("Column 1: "+[Link](1));
JBTA-PG-4/4/07 35
[Link]("Column 2: "+[Link](2));
}
[Link]().commit(true);
}
catch (Exception ex)
{
[Link]();
[Link](0);
}
}
catch (Exception sysEx)
{
[Link]();
[Link](0);
}
}
The db parameters specified in the property file are assumed to be in the format:
• DB_x_DatabaseURL=
• DB_x_DatabaseUser=
• DB_x_DatabasePassword=
• DB_x_DatabaseDynamicClass=
Note: Some error handling code has been removed from this text for ease of
readability purposes.
/*
* Some XAResourceRecovery implementations will do their startup work here,
* and then do little or nothing in setDetails. Since this one needs to know
* dynamic class name, the constructor does nothing.
*/
36 JBTA-PG-04/04/07
Examples
{
numberOfConnections = 1;
connectionIndex = 0;
props = null;
}
/**
* The recovery module will have chopped off this class name already. The
* parameter should specify a property file from which the url, user name,
* password, etc. can be read.
*
* @message [Link] An exception
* occurred during initialisation.
*/
if (breakPosition != -1)
{
fileName = [Link](0, breakPosition - 1);
try
{
numberOfConnections = [Link](parameter
.substring(breakPosition + 1));
}
catch (NumberFormatException e)
{
return false;
}
}
try
{
String uri = [Link]
.locateFile(fileName);
[Link]([Link]
.getName(), uri);
props = [Link]();
}
catch (Exception e)
{
return false;
}
return true;
}
/**
* @message [Link] {0} could not find
* information for connection!
*/
if (hasMoreResources())
{
connectionIndex++;
conn = getStandardConnection();
JBTA-PG-4/4/07 37
}
return [Link]().getConnection().getXAResource();
}
if (theUser != null)
{
[Link]([Link], theUser);
[Link]([Link], thePassword);
String dc = [Link](dynamicClass);
if (dc != null)
[Link]([Link], dc);
if (theUser != null)
{
[Link]([Link], theUser);
[Link]([Link], thePassword);
38 JBTA-PG-04/04/07
Examples
/*
* Example:
*
* DB2_DatabaseURL=jdbc\:arjuna\:sequelink\://qa02\:20001
* DB2_DatabaseUser=tester2 DB2_DatabasePassword=tester
* DB2_DatabaseDynamicClass=[Link].sequelink_5_1
*
* DB_JNDI_DatabaseURL=jdbc\:arjuna\:jndi DB_JNDI_DatabaseUser=tester1
* DB_JNDI_DatabasePassword=tester DB_JNDI_DatabaseName=empay
* DB_JNDI_Host=qa02 DB_JNDI_Port=20000
*/
JBTA-PG-4/4/07 39
Chapter 7
Configuring JBossJTA
Configuration options
The following table shows the configuration features, with default values shown in italics.
For more detailed information, the relevant section numbers are provided.
40 JBTA-PG-04/04/07
Using JBossJTA in application servers
Chapter 8
Using JBossJTA in
application servers
JBOSS Application Server
Configuration
Service Configuration
The JBoss Transaction Service is configured primarily via the XML files stored in the etc
directory, but when run as a JBOSS service there are a number of configurable attributes
available. They are as follows:
StatisticsEnabled – This determines whether or not the transaction service should gather
statistical information. This information can then be viewed using the PerformanceStatistics
MBean. Specified as a Boolean. The default is to not gather this information.
<mbean code="[Link]"
name="jboss:service=TransactionManager">
<attribute name="TransactionTimeout">300</attribute>
<attribute name="StatisticsEnabled">true</attribute>
</mbean>
The transaction service is configurable also via the standard JBoss Transaction Service
property files. These are located in the JBossTS install location under the etc sub-directory.
These files can be edited manually or through JMX. Each property file is exposed via an
object with the name [Link] and an attribute of module
where module is equal to the name of the module to be configured, e.g.
[Link]:module=arjuna.
JBTA-PG-4/4/07 41
Logging
In order to make JBossTS logging semantically consistent with JBossAS, the
TransactionManagerService modifies the level of some log messages. This is achieved by
overriding the value of the [Link] property given in the jbossjta-
[Link] file. Therefore, the value of this property will have no effect on the logging
behaviour when running embedded in JBossAS. By forcing use of the log4j_releveler logger,
the TransactionManagerService causes all INFO level messages in the transaction code to be
modified to behave as DEBUG messages. Therefore, these messages will not appear in log
files if the filter level is INFO. All other log messages behave as normal.
The services
There is currently one service offered by the JBOSS integration. In this section we shall
discuss what this service does.
TransactionManagerService
The transaction manager service’s main purpose is to ensure the recovery manager is started.
It also binds the JBossTS JTA transaction manager to java:/TransactionManager
name with the JNDI provider. This service depends upon the existence of the CORBA ORB
Service and it must be using JacORB as the underlying ORB implementation.
• distributed: this uses the JTS enabled transaction manager implementation and
hence supports distributed transactions and recovery. To configure this use the
[Link] class. This
is the default configuration.
• local: this uses the purely local JTA implementation. To configure this use the
[Link] class.
[Link]( new
[Link]() );
42 JBTA-PG-04/04/07
Index
Index
AutoCommit, 32 Relationship to JTA, 28
Configurable options, 39 Supported JDBC drivers, 26
DataSource, 28 Thread restrictions, 12
Dynamic class instantiation, 29 suspending and resuming transactions, 13
Enlisting resources, 14 terminating transactions, 13
Example, 33 Transaction synchronization, 14
Failure recovery, 23 Transactional drivers, 27
JBoss Transactions compliance, 10 Transactional Objects for Java
JBoss Transactions restrictions, 26 configuration, 39
JDBC 2.0, 26 TransactionManager, 11
properties, 28 Transactions
JDBC2 Recovery, 23 global default timeout value, 20
JNDI string extension, 29 timeout values, 20
Loading drivers, 27 UserTransaction, 11
Making connections, 28 Using connections, 31
Obtaining TransactionManager, 11 XAConnectionRecovery, 22, 23
Obtaining UserTransaction, 11 XADataSource, 28
Package, 11 XAResource, 16, 28
Property variables failure recovery, 22
XAConnectionRecovery, 23 setTransactionTimeout, 20
JBTA-PG-4/4/07 43