How to Close an MQ Connection From Java
Closing an MQ connection in Java helps you to immediately free up the significant resources allocated to the connection, instead of waiting for Java's garbage collector to reclaim the resources later. The MQ JMS extensions provide functionality for your Java program to dynamically create connection factories and destinations at run time. The extensions provide an alternative to calling the connection factories as administered objects from the JNDI (Java Naming and Directory Interface). Call the "close" method to close the MQ connection once you're done using it.
Instructions
-
-
1
Open your Java file in an editor such as Eclipse, Netbeans or JBuilder X.
-
2
Add the following code at the top of your file to import the necessary JMS and MQ packages:
import com.ibm.jms.*;
import com.ibm.mq.jms.*;
-
-
3
Add the following code in your function to create an MQ connection factory and initialize it with values:
MQConnectionFactory my_mq_factory = new MQConnectionFactory();
my_mq_factory.setHostName("host");
my_mq_factory.setTransportType(WMQConstants.WMQ_CM_CLIENT);
my_mq_factory.setQueueManager("QM1");
my_mq_factory.setChannel("QM1.SVR");
my_mq_factory.setPort(1400);
-
4
Add the following code to create a JMS connection and session with your "MQConnectionFactory" object:
Connection my_jms_conn = null;
Session my_jms_session = null;
my_jms_conn = (Connection) my_mq_factory.createConnection();
my_jms_session = my_jms_conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
5
Add the following code to close the MQ connection and session with the "close" method once you're finished using them:
if (my_jms_conn != null)
my_jms_conn.close();
if (my_jms_session != null)
my_jms_session.close();
-
6
Save the Java file, compile and execute the program to open and then close an MQ connection.
-
1
Tips & Warnings
Don't attempt to close an MQ connection with the "stop" method because it only temporarily stops incoming messages.