I am currently creating a new connection, session and sender (aka producer) each time I have to send a message. My code looks like:
javax.naming.Context initialContext = new InitialContext();
QueueConnectionFactory connectionFactory = (QueueConnectionFactory) initialContext.lookup("ConnectionFactory");
queueConnection = connectionFactory.createQueueConnection("user", "pass");
queue = (Queue) initialContext.lookup(queueName);
jmsSession = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
queueConnection.start();
sender = jmsSession.createSender(queue);
messages are then sent to the sender using the send() method.
I see from the documentation that this is considered to be an anti-pattern and that Connection/Session/Producer/Consumers should be reused. However, I've read some posts online stating that accessing objects other than the ConnectionFactory or the Connection from multiple threads is dangerous.
Could I get some clarification on this? If multiple threads are sending messages, can I reuse the Session, Producer and Sender objects... or should they be created each time and only reuse the Connection?
I know this question is asked all over the place and there's even an article on the topic at http://community.jboss.org/wiki/ShouldIcacheJMSconnectionsandJMSsessions but most don't mention thread safety, so I'd like to get some definitive advice on this matter.
On a related note, if one does reuse a previously initialized Connection/Session/Producer/Consumers object, how should you determine if it's still alive? I don't see an API for this... and I assume checking if it's null isn't sufficient.
Thanks,
J