Bug S2095 reported when returning an AutoCloseable


I have a false positive S2095 with SonarLint V5.2.0.35150 running in IntelliJ 2021.2.1 Ultimate.

I use a class that implements the AutoCloseable interface. The class is instantiated and initialized in a builder method. The returned instance is used in a try-with-resources.

The code looks like this:

private class SomeAutoCloseable implements AutoCloseable {
      // Whatever methods

      // This is the close method of the AutoCloseable interface
      public void close() {
      // Clean up the instance

private void aWorkerMethod() {
   // The AutoCloseable object is used here in a try-with-resources
   try (SomeAutoCloseable sac = aBuilderMethod()) {
   // Use the SomeAutoCloseable instance

private SomeAutoCloseable aBuilderMethod() {
     final SomeAutoCloseable result = new SomeAutoCloseable();
      // Fill the SomeAutoCloseable and return it as the result of the builder method
     return result;

SonarLint shows a bug S2095 in the line

 final SomeAutoCloseable result = new SomeAutoCloseable();

in the method aBuilderMethod and complains that the instance should be closed. However, the instance is returned as the result of the method and this returned instance is used in a try-with-resources. It does not make sense to close it in the builder method.

1 Like

To add to the legit concern of the original poster here’s another similar situation where this rule produces false-positives:

		jdbcTemplate.update(new PreparedStatementCreator() {
			public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
				PreparedStatement ps = con.prepareStatement(MessageConstant.INSERT_CUSTOM_RNSD_SCREEN_QUERY,
						new String[] { "SCREEN_ID" });
				ps.setString(1, request.getScreenName());
				ps.setString(2, request.getScreenType());
				ps.setString(3, request.getForeignUserGroup());
				ps.setTimestamp(4, new Timestamp(System.currentTimeMillis()));
				ps.setString(5, request.getCreatedBy());
				return ps;
		}, keyHolder);

The “jdbcTemplate” above is a Spring JdbcTemplate. I’ve verified that JdbcTemplate’s “update” method does close the prepared statement in a finally block.

Also note that this other similar bug report exists for java:S2095.