background image

Produce and Synchronously Receive Messages

<< Using the JMS API | Using Message-Driven Beans >>
<< Using the JMS API | Using Message-Driven Beans >>

Produce and Synchronously Receive Messages

@Resource(mappedName=
"jms/ConnectionFactory")
private ConnectionFactory connectionFactory;
@Resource(mappedName=
"jms/Topic")
private Topic topic;
If you declare the resource static, runtime errors will result.
Using Session Beans to Produce and to Synchronously
Receive Messages
A Java EE application that produces messages or synchronously receives them can use a session
bean to perform these operations. The example in
"A Java EE Application That Uses the JMS
API with a Session Bean" on page 964
uses a stateless session bean to publish messages to a topic.
Because a blocking synchronous receive ties up server resources, it is not a good programming
practice to use such a receive call in an enterprise bean. Instead, use a timed synchronous
receive, or use a message-driven bean to receive messages asynchronously. For details about
blocking and timed synchronous receives, see
"Writing the Client Programs for the
Synchronous Receive Example" on page 912
.
Using the JMS API in a Java EE application is in many ways similar to using it in a stand-alone
client. The main differences are in resource management and transactions.
Resource Management
The JMS API resources are a JMS API connection and a JMS API session. In general, it is
important to release JMS resources when they are no longer being used. Here are some useful
practices to follow.
If you wish to maintain a JMS API resource only for the life span of a business method, it is a
good idea to close the resource in a finally block within the method.
If you would like to maintain a JMS API resource for the life span of an enterprise bean
instance, it is a good idea to use a @PostConstruct callback method to create the resource
and to use a @PreDestroy callback method to close the resource. If you use a stateful session
bean and you wish to maintain the JMS API resource in a cached state, you must close the
resource in a @PrePassivate callback method and set its value to null, and you must create
it again in a @PostActivate callback method.
Transactions
Instead of using local transactions, you use container-managed transactions for bean methods
that perform sends or receives, allowing the EJB container to handle transaction demarcation.
Because container-managed transactions are the default, you do not have to use an annotation
to specify them.
Using the JMS API in a Java EE Application
Chapter 31 · The Java Message Service API
955