Search code examples
javasonarqubedatabase-connectionsonarlint

Sonar squid:S2095 when method return Connection


Returning Connection using a method is a common practice, For example in Hikari's HikariConnectionProvider

public Connection getConnection() throws SQLException
   {
      Connection conn = null;
      if (this.hds != null) {
         conn = this.hds.getConnection();
      }   
      return conn;
   }

But Sonar warns about closing connection

Connections, streams, files, and other classes that implement the Closeable interface or its super-interface, AutoCloseable, needs to be closed after use. Further, that close call must be made in a finally block otherwise an exception could keep the call from being made.

I want to return a Connection I can use later, so I can't close it in those methods

How/if can I avoid such warning on main method to return valid connection?

EDIT Added a false positive bug in Sonar community: S2095 report on method return Connection

EDIT 2 Issue isn’t reproducible on latest version


Solution

  • Technically speaking, SonarQube (and in this instance, the SonarJava analyzer) has no guarantee that the connection returned by this method will ultimately be closed - hence the issue.

    If you are confident that your code base has all the required resource-cleaning code in place somewhere else, my suggestion here is to mark this particular issue as Won't fix in the SonarQube UI.