Detect when an AutoCloseable instance is called in a call chain


(Gabriel Belingueres) #1

Description: When in a method call chain, an instance of an AutoCloseable is returned and used, then the object can not be properly closed, therefore producing a resource leak.
Snippet Noncompliant Code:
try ( PreparedStatement ps =
DriverManager.getConnection( “jdbc:hsqldb:mem:testdb”, “sa”, “” ).prepareStatement( “select * from table” ) )
{ …
}
// PreparedStatement will be closed. Connection will NOT be closed.

Snipped of Compliant Code:
// Always handle an AutoCloseable instance through a variable or parameter. try ( Connection connection = DriverManager.getConnection( "jdbc:hsqldb:mem:testdb", "sa", "" ); PreparedStatement ps = connection.prepareStatement( "select * from table" ) ) { ... }
type: Bug