10000 As getAll method returns a Stream, we cannot close the involved · prog012/java-design-patterns@a1a4088 · GitHub
[go: up one dir, main page]

Skip to content

Commit a1a4088

Browse files
committed
As getAll method returns a Stream, we cannot close the involved
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.
1 parent cbba487 commit a1a4088

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

dao/src/main/java/com/iluwatar/dao/DbCustomerDao.java

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,8 @@ public Stream<Customer> getAll() throws Exception {
6565
Connection connection;
6666
try {
6767
connection = getConnection();
68-
PreparedStatement statement = connection.prepareStatement("SELECT * FROM CUSTOMERS");
69-
ResultSet resultSet = statement.executeQuery();
68+
PreparedStatement statement = connection.prepareStatement("SELECT * FROM CUSTOMERS"); //NOSONAR
69+
ResultSet resultSet = statement.executeQuery(); //NOSONAR
7070
return StreamSupport.stream(new Spliterators.AbstractSpliterator<Customer>(Long.MAX_VALUE,
7171
Spliterator.ORDERED) {
7272

@@ -82,7 +82,7 @@ public boolean tryAdvance(Consumer<? super Customer> action) {
8282
throw new RuntimeException(e);
8383
}
8484
}
85-
}, false).onClose(() -> mutedClose(connection));
85+
}, false).onClose(() -> mutedClose(connection, statement, resultSet));
8686
} catch (SQLException e) {
8787
throw new Exception(e.getMessage(), e);
8888
}
@@ -92,8 +92,10 @@ private Connection getConnection() throws SQLException {
9292
return dataSource.getConnection();
9393
}
9494

95-
private void mutedClose(Connection connection) {
95+
private void mutedClose(Connection connection, PreparedStatement statement, ResultSet resultSet) {
9696
try {
97+
resultSet.close();
98+
statement.close();
9799
connection.close();
98100
} catch (SQLException e) {
99101
e.printStackTrace();

0 commit comments

Comments
 (0)
0