Kambiz
Kambiz

Reputation: 109

Is the java Garbage collector responsible to release the JMS connection after connection.close()

I am using GlassFish JMS ConnectionFactory. Connection is closed in finally. and Maximum Pool Size is set to 5.

Test Case: I sent 10 messages constantly within 3 seconds from invoker().

Result: First 5 messages sent successfully and message 6 onward failed to allocate more connections. It means all previous 5 connections were still open.

Question 1: How long does it take to release the connection poll after connection.close()?

Question 2: Is the Garbage collector responsible to release the connection after JMS connection.close()?

This is my simple message client which sends messages to the queue

private void invoker(String id){

    Connection connection = null;
    Session session = null;
    MessageProducer messageProducer = null;
    TextMessage message = null;
    try {
        connection = connectionFactory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        messageProducer = session.createProducer(successfulQueue);
        String msg = id;
        message = session.createTextMessage(msg);
        messageProducer.send(message);
        log.info("Successful message is Sent to ProcessQueue: [" + msg + "]");
    }
    catch (Exception e) {
        log.error(e);
    }
    finally {
        if (messageProducer != null) {
            try {
                messageProducer.close();
            }
            catch (JMSException e) {
                log.error(e);
            }
        }
        if (session != null) {
            try {
                session.close();
            }
            catch (JMSException e) {
                log.error(e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            }
            catch (JMSException e) {
                log.error(e);
            }
        }
    }

Upvotes: 2

Views: 628

Answers (1)

Koustav Ray
Koustav Ray

Reputation: 1142

Answer to your 2nd Question is The Connection is not closed by the GC but instead the background process that KeepsAlive the connection is terminated by connection.close() (For How GC works read: https://www.quora.com/How-does-garbage-collection-work-in-the-JVM)

Recommendation: Try using A PooledConnectionFactory and do a .stop() on the same apart from connection.close

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {

    if (connection != null || pcf != null) try {
          connection.close();
    //pcf.stop();
    }
    catch (JMSException e) {
         //log
    }

Upvotes: 0

Related Questions