João João - 1 month ago 9
Java Question

Long lived JMS sessions. Is Keeping JMS connections / JMS sessions allways open a bad pratice?

Is keeping JMS connections / sessions / consumer always open a bad practice?

Code draft example:

// app startup code

ConnectionFactory cf = (ConnectionFactory)jndiContext.lookup(CF_JNDI_NAME);
Connection connection = cf.createConnection(user,pass);
Session session = connection.createSession(true,Session.TRANSACTIONAL);
MessageConsumer consumer = session.createConsumer(new Queue(queueName));
consumer.setMessageListener(new MyListener());
connection.start();
connection.setExceptionListener(new MyExceptionHandler()); // handle connection error


// ... Message are processed on MyListener asynchronously ...


// app shutdown code

consumer.close();
session.close();
connection.close();


Any suggestions to improve this pattern of JMS usage?

Answer

That is a very common and acceptable practice when dealing with long lived connections. For many JMS servers it is in fact preferable to creating a new connection each time it is needed.

Comments