You are creating a connection in a method called createConnection()
. Specifically, of a JMS/MQ connection type.
It looks like your class expects the connection to be long-running and reusable. — In classes like this, createConnection()
method(s) should be paired with a method to close the opened connection.
The right approach would be: your class should also implement the Closeable
or AutoCloseable
interface to hint that the caller have the responsibility to call the close method once they are finished using it.
This approach would also have the side effect that the caller of your class will have Sonar (if enabled) warn them to: Use try-with-resources or close this "Connection" in a "finally" clause
if they forgot to do so.
Which interface to implement?
In your case, you use MQConnectionFactory
which logically will create connections of type MQConnection
; and from its javadoc spec, MQConnection
implements AutoCloseable
. We can copy MQConnection
's close()
method signature as a reference for our close method, and to match the handled connection type.
So, in your class, it would be something like this:
public class MyMQHelper implements AutoCloseable {
private MQConnection connection; // result from createConnection() should be set to this variable
private Connection createConnection() throws JMSException { /* ... */ }
@Override
public void close() throws JMSException {
if (connection != null) connection.close();
}
}
Sonar warning
The Sonar rule is for general use case using the open-use-close mechanism. When you have specialized use case like this, you can choose to ignore the error further, either by marking it as WONTFIX
in SonarQube, or by using suppression hint to block the specific warning (you need to know the Sonar rule id):
private Connection createConnection() throws JMSException {
MQConnectionFactory mqCF = new MQConnectionFactory();
...
@SuppressWarnings("java:S2095") // by design: Connection is for use later
Connection connection = mqCF.createConnection(...);
connection.start();
return connection;
}
Closing
Having the createConnection()
as a private method may signify that your class handles much more than a connection management role, and may be part of a long-running service or job.
However, there should be an orchestrator class whose job is to initialize the required classes before going to the main service or job loop. This is where the (direct/indirect) call to createConnection()
should happen and should be paired with the close()
call (either explicitly or implicitly using try-with-resources statement).