Skip to content

Commit

Permalink
As getAll method returns a Stream, we cannot close the involved
Browse files Browse the repository at this point in the history
resources (Connection, Statement and resultSet) until the stream is
closed by the consumer. So try-with-resources is not an option as per
sonarqube’s recommendation. But it is still recommended to close
statement and result set. When connection pool used, connection is not
closed when close() called. It is just returned to the pool.

Using //NOSONAR to avoid false blocker issue.
  • Loading branch information
mookkiah committed Aug 13, 2017
1 parent cbba487 commit a1a4088
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions dao/src/main/java/com/iluwatar/dao/DbCustomerDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ public Stream<Customer> getAll() throws Exception {
Connection connection;
try {
connection = getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT * FROM CUSTOMERS");
ResultSet resultSet = statement.executeQuery();
PreparedStatement statement = connection.prepareStatement("SELECT * FROM CUSTOMERS"); //NOSONAR
ResultSet resultSet = statement.executeQuery(); //NOSONAR
return StreamSupport.stream(new Spliterators.AbstractSpliterator<Customer>(Long.MAX_VALUE,
Spliterator.ORDERED) {

Expand All @@ -82,7 +82,7 @@ public boolean tryAdvance(Consumer<? super Customer> action) {
throw new RuntimeException(e);
}
}
}, false).onClose(() -> mutedClose(connection));
}, false).onClose(() -> mutedClose(connection, statement, resultSet));
} catch (SQLException e) {
throw new Exception(e.getMessage(), e);
}
Expand All @@ -92,8 +92,10 @@ private Connection getConnection() throws SQLException {
return dataSource.getConnection();
}

private void mutedClose(Connection connection) {
private void mutedClose(Connection connection, PreparedStatement statement, ResultSet resultSet) {
try {
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
Expand Down

0 comments on commit a1a4088

Please sign in to comment.