background image

JMS Connections

<< JMS Connection Factories | JMS Sessions >>
<< JMS Connection Factories | JMS Sessions >>

JMS Connections

In addition to injecting a connection factory resource into a client program, you usually inject a
destination resource. Unlike connection factories, destinations are specific to one domain or
the other. To create an application that allows you to use the same code for both topics and
queues, you assign the destination to a Destination object.
The following code specifies two resources, a queue and a topic. The resource names are
mapped to destinations created in the JNDI namespace.
@Resource(mappedName=
"jms/Queue")
private static Queue queue;
@Resource(mappedName=
"jms/Topic")
private static Topic topic;
With the common interfaces, you can mix or match connection factories and destinations. That
is, in addition to using the ConnectionFactory interface, you can inject a
QueueConnectionFactory
resource and use it with a Topic, and you can inject a
TopicConnectionFactory
resource and use it with a Queue. The behavior of the application will
depend on the kind of destination you use and not on the kind of connection factory you use.
JMS Connections
A connection encapsulates a virtual connection with a JMS provider. A connection could
represent an open TCP/IP socket between a client and a provider service daemon. You use a
connection to create one or more sessions.
Connections implement the Connection interface. When you have a ConnectionFactory
object, you can use it to create a Connection:
Connection connection = connectionFactory.createConnection();
Before an application completes, you must close any connections that you have created. Failure
to close a connection can cause resources not to be released by the JMS provider. Closing a
connection also closes its sessions and their message producers and message consumers.
connection.close();
Before your application can consume messages, you must call the connection's start method;
for details, see
"JMS Message Consumers" on page 905
. If you want to stop message delivery
temporarily without closing the connection, you call the stop method.
The JMS API Programming Model
Chapter 31 · The Java Message Service API
903