java - Why compiler warns about resource leak? -
i cannot understand why compiler warns me resource leak (resource leak: 'conn' not closed @ location
) in following code:
connection conn = null; try { conn = databaseconnectionpool.getconnectionfrompool(); // code try { // other code } catch (final someexception e) { // more code throw e; // resource leak: 'conn' not closed @ location } } catch (final sqlexception | otherexceptions e) { // more code } { try { // bunch of code } { databaseconnectionpool.freeconnection(conn); } }
note if write this
connection conn = null; try { conn = databaseconnectionpool.getconnectionfrompool(); // code try { // other code } catch (final someexception e) { // more code throw e; } { databaseconnectionpool.freeconnection(conn); } } catch (final sqlexception | otherexceptions e) { // more code } { // bunch of code }
the warning gone.
the compiler quite dump. cannot know databaseconnectionpool.freeconnection(conn)
call close
on conn
. not sure why second example not trigger warning, feature not totally perfect , can yield false negatives. basically, resource should closed calling close
method directly @ place resource acquired; way compiler can figure out want close it, not inter-procedural analysis check if called function calls close
.
with java7, should consider using try-with-resource statement; the encouraged way handle resources, i.e.:
try(connection conn = ...){ // conn // no close necessary here, done implicitly try statement }
your whole pattern of closing connection calling method other close
seems flawed me (it works, discourage usage): resource should able close calling close
. if resource requires databaseconnectionpool.freeconnection
called close it, violating java's resource contract. if use try-with-resource statement, have no choice anyway: statement call close
, not method.
Comments
Post a Comment