Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long lived JMS sessions. Is Keeping JMS connections / JMS sessions always opened a bad practice?

Tags:

java

jms

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?

like image 474
João Avatar asked Nov 07 '08 23:11

João


3 Answers

Agreed. Here are some good tips on how to use JMS efficiently which includes keeping around connections/sessions/producers/consumers.

You might also want to check the recommendation on using transactions too if you are interested in maximising performance.

like image 78
James Strachan Avatar answered Oct 16 '22 16:10

James Strachan


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.

like image 21
John Meagher Avatar answered Oct 16 '22 16:10

John Meagher


The choice of keeping connection/session/producer/consumer open for long or not should be based on the frequency at which producer/consumer sends/receives messages.

If a producer sends or a consumer receives messages frequently then the connections/sessions/producer/consumer should be kept open. On the other hand if messages send/receive is infrequent then it is not good keeping these JMS objects open will consume system resources like sockets.

like image 37
Shashi Avatar answered Oct 16 '22 15:10

Shashi