background image

Using JMS API Local Transactions

<< Connection Factory without Client ID | Difference of Messaging and Synchronized Processing >>
<< Connection Factory without Client ID | Difference of Messaging and Synchronized Processing >>

Using JMS API Local Transactions

Using JMS API Local Transactions
You can group a series of operations into an atomic unit of work called a transaction. If any one
of the operations fails, the transaction can be rolled back, and the operations can be attempted
again from the beginning. If all the operations succeed, the transaction can be committed.
In a JMS client, you can use local transactions to group message sends and receives. The JMS
API Session interface provides commit and rollback methods that you can use in a JMS client.
A transaction commit means that all produced messages are sent and all consumed messages
are acknowledged. A transaction rollback means that all produced messages are destroyed and
all consumed messages are recovered and redelivered unless they have expired (see
"Allowing
Messages to Expire" on page 941
).
A transacted session is always involved in a transaction. As soon as the commit or the rollback
method is called, one transaction ends and another transaction begins. Closing a transacted
session rolls back its transaction in progress, including any pending sends and receives.
In an Enterprise JavaBeans component, you cannot use the Session.commit and
Session.rollback
methods. Instead, you use distributed transactions, which are described in
"Using the JMS API in a Java EE Application" on page 954
.
You can combine several sends and receives in a single JMS API local transaction. If you do so,
you need to be careful about the order of the operations. You will have no problems if the
transaction consists of all sends or all receives or if the receives come before the sends. But if you
try to use a request/reply mechanism, whereby you send a message and then try to receive a
reply to the sent message in the same transaction, the program will hang, because the send
cannot take place until the transaction is committed. The following code fragment illustrates
the problem:
// Don
't do this!
outMsg.setJMSReplyTo(replyQueue);
producer.send(outQueue, outMsg);
consumer = session.createConsumer(replyQueue);
inMsg = consumer.receive();
session.commit();
Because a message sent during a transaction is not actually sent until the transaction is
committed, the transaction cannot contain any receives that depend on that message's having
been sent.
In addition, the production and the consumption of a message cannot both be part of the same
transaction. The reason is that the transactions take place between the clients and the JMS
provider, which intervenes between the production and the consumption of the message.
Figure 31­9
illustrates this interaction.
Creating Robust JMS Applications
Chapter 31 · The Java Message Service API
947