2
votes

In my java swing application i've implemented a jms client which communicates with a jms server. This works fine.

Currently when my application starts i create a connection and a session:

ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

Next when i need to send a message to a topic i create a topic (to send the message to), a temp queue (to receive replies), a producer (to send the message) and a consumer (to actual read the replies):

Destination destination = session.createTopic ...
MessageProducer producer = session.createProducer ...
Destination tempDest = session.createTemporaryQueue(); 
MessageConsumer responseConsumer = session.createConsumer(tempDest);
producer.send(msg);

I was wondering what is the best practice in this case?

Can i simply create everything when i need to send a message or may it be better to save the Destination, MessageProducer , MessageConsumer somewhere and re-use it. Is there something special i need to pay attention to when i decide to re-use the objects?

1

1 Answers

3
votes

You should reuse the objects that you are able to reuse.

The connection could probably be resused for your entire application, as it's thread safe.

The session object is not thread safe, and you should stick to a session per thread in that case.

You can cheat. Use the org.apache.activemq.pool.PooledConnectionFactory and it will setup a pool of sessions, connections and producers.

You still have to write connection.createSession(.. and session.close() but that does just take and release objects from the pool.

It might be easier to actually reuse your objects, if you have fine grained control over your concurrency, which is seldom the case.