1 Reply Latest reply on Sep 29, 2011 3:57 PM by Clebert Suconic

    Thread safety when reusing objects

    jhannah Newbie

      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);
      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.





        • 1. Re: Thread safety when reusing objects
          Clebert Suconic Master

          It's not really bound to the thread usage....



          It's more thinking like a session...



          If you always access a session within a thread at any point.. then you're fine.



          Like: having multiple consumers from a same session. when you call commit, you will commit for both consumers.


          If you use the session, place it on a pool and reuse it later from a different thread.. it's fine.



          Those are JMS concepts.. not anything specific to HornetQ.