If i have the following method –
public static void C() {
Connection con = DriverManager.getConnection();
.... // code
return;
}
and i dont call con.close() , will the connection terminate automatically once the method returns?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No, it won’t. It may or may not eventually close, but it’s going to be a long time before it does, if ever. The connection class’s finalizer probably closes the connection if it’s open, but there are lots of situations where finalizers aren’t ever run. It’s essential to call
con.close()explicitly.Here’s how I usually handle it (although I’ve factored a lot of this logic out into helpers, since this is verbose otherwise):
Note that having detected the unclosed connection in the
finallyclause, I close it but don’t allow any exception doing so may cause to get thrown. This is because the main logic closes the connection correctly, which means that if I’ve found an open connection in thefinallyblock, an exception has already been thrown and we’re handling it, so I don’t want to mask that by throwing a different exception fromcon.close().With decent helpers, that gets a lot shorter and easier to write:
…where JDBCHelper (a hypothetical class) contains: