JMS Class Model Complexity: Simplification Needed
The JMS class model is a complex structure that can be tedious to code to and difficult to remember. It can also result in a lot of duplicate code within your application, some for working with JMS topics and the rest for JMS queues. This section describes the highly involved sequence of code that JMS requires.
To use JMS, you first must get a connection to your JMS provider. Through JNDI, retrieve the
javax.jms.ConnectionFactory object, which you'll use to get this connection in the form of a
javax.jms.Connection object (For an overview of JNDI, read the sidebar, "Java Naming and Directory Interface (JNDI)".).
In JMS, messages are sent to, or received from, a destination. The
javax.jms.Destination class is the base class to the more familiar
javax.jms.Queue classes. We'll discuss these classes in more detail as we go along.
You must create a
javax.jms.Session object for every
javax.jms.Destination in which your application is interested. To create a Session object you must call the appropriate method on the Connection object. Each Session can be used by only one thread at a time. This means that for two or more threads to listen to the same Destination, they each must retrieve their own instance of a Session object for that Destination.
In turn, you use a Session object to create a
javax.jms.MessageProducer object to send messages to a Destination, a
javax.jms.MessageConsumer object to receive messages, and the
javax.jms.Message objects themselves.
All the classes discussed so far are actually abstract interfaces, thus they cannot be instantiated themselves. Instead, JMS defines more specific classes that extend these interfaces.
To clarify, the UML diagram in Figure 2 illustrates the extended class model for the
|Figure 2: The JMS Connection and Session Types|
You must know ahead of time whether you will need a
QueueConnectionFactory, or both. References to these objects also are retrieved through JNDI. The only difference between the two connection factory classes is the type of Connection object each one creates: a
TopicConnection or a
QueueConnection. In turn, the only difference between these two connection objects is the type of Session object each one creates: a
TopicSession or a
The UML diagram in Figure 3 illustrates the class model for the remaining classes,
Queue classes are subclasses of the Destination super class. Typically, destinations are created ahead of time through an administration interface on your JMS Provider. However, a
QueueSession object can create
Queue objects at runtime, respectively.
QueueSender classes extend
MessageProducer, and they send messages to a
Queue, respectively. Similarly, the
QueueReceiver classes extend
MessageConsumer, and they receive messages from a
For the sakes of improvement and simplification, you should create a JMS Facade class.