2
votes

We experience latencies issues on our network. I have a 1ms penalty for each connection, session and producer creation. It's why I would like to cache my jms connection, session and MessageProducer in my stateless EJB instance variable.

I could create them in the @PostConstruct, is it safe to do that?

@Stateless
public class MyEJB {
    @Resource(mappedName = Messaging.LOCAL_JNDI_CONN_FACTORY)
    private ConnectionFactory connectionFactory;

    @Resource(mappedName = AutoRecolteIndexerConsumer.QUEUE_NAME)
    private Queue queue;

    private Connection connection;
    private Session session;
    private MessageProducer producer;


    @PostConstruct
    public void init() {
        connection = connectionFactory.createConnection();// 1ms
        session = connection.createSession(true, Session.SESSION_TRANSACTED);// 1ms
        producer = session.createProducer(queue); //1ms
    }

    public void send(Object data) {
        ObjectMessage obj = session.createObjectMessage();
        obj.setObject(data);
        producer.send(obj);
    }

}
1

1 Answers

2
votes

There's nothing wrong with pre-initializing heavy weight objects like connection factories, connections, and sessions, in fact, it's good practice since we don't want to create those things each time we send a message.

But I think you're confusing stateless and stateful EJB's. You are initializing the bean's state, so it's not stateless, it's stateful. Second, since you have state, your code should assume worst case scenario and clean up resources should an error occur, like this...

   public void send(Object data) {
        ObjectMessage obj = session.createObjectMessage();
        obj.setObject(data);
        try{
           producer.send(obj);

        }catch( JMSException jex){
          producer.close();
          session.close();
          connection.close();
          throw new EJBException( jex);
        }
    }

Avoid resource leaks by cleaning up, then throw EJBException so the container destroys the EJB instance and creates a new one in its place.