1
votes

I'm working on an older application and upgrade it's JMS system from JBoss Messaging to HornetQ, in the process I've run into a few gotchas that seem to be related to how this application uses and manages JMS connections. This is my first large scale exposure to JMS (besides simple toy usage) so I'm wondering if the current idiom is... correct, silly, or dead wrong?

Here is how the current system works.

static QueueConnection connection;
static boolean isConnected;

static void sendSomeMessage(Object sendMe) {
   if(!isConnected) connect();

}

static void connect() {
    // jndi lookup for connection factory
    connection = factory.createQueueConnection();

    // lambdas in java pseudo code, woot!
    connection.onException => disconnect();
    connection.start();
    isConnected = true;
}

static void disconnect() {
    connection.close()
    isConnected = false;
}

The gist of this is that the connection is used over and over for every single message that is sent until an error occurs, when an error occurs the connection finally gets closed and recreated.

Every example that I've seen always creates a new connection factory and a new connection for every message but these examples are not big system examples they are one off "how-to" examples.

Is keeping a single managed reference to a JMS Connection an acceptable idiom, should the connection factory be cached? Should they both be recreated for every new message?

It makes sense to me to reuse the connection factory but use a fresh connection every time?

1

1 Answers

1
votes

Message systems are supposed to be asynchronous...

So, you should keep a connection open for the entire life of your application.

JMS is currently a bit verbose on objects you have to create, so you have to create a connection and a session.

So you should do this:

connection = cf.createConnection(...);

session = connection.createSession(...);

producer = session.createProducer(...);

The session and producer should always be used within a thread. As a session represents a thread usage. (You may reuse it within multiple threads as long as it's synchronized)