简体   繁体   中英

java.sql.Connection leakage issue

I have a class which takes a database connection over constructor, as you can see from the sample code connCat = con_cat (con_cat is being passed in).

Please let me know: do I need to explicitly close the connCat connection inside this class, so the connection will be released properly?

If it's missing, will it cause connection leakage?

Will having a finally clause and doing connCat.close(); and connCat = null; be enough?

public class GenericDbProc extends DBProcessor {
Logger fileLogger = Logger.getLogger(GenericDbProc.class);
Connection connCat;

public GenericDbProc(Connection con_cat)
{
    connCat = con_cat;
}

public List<MxsCustomParam> getServiceEndPointDetails(String module_name) {
    StringBuffer sb = new StringBuffer();
    PreparedStatement stmt = null;
    ResultSet rs = null;
    
    sb.append("select xxxxxxx ")
            .append(" where module = ?");
    List<MxsCustomParam> mxsCustomParamList = new ArrayList<MxsCustomParam>();

    try {
        stmt = connCat.prepareStatement(sb.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        stmt.setString(1, module_name);
        
        rs = stmt.executeQuery();

You get the connection passed over the constructor from the outside. I'd say that closing the connection should not be managed here, but on the outside too.

And yes, the connection should be closed once it is not needed any more, as it holds a socket open in the background and there is a limit to how many connections you can open. If you simply release the reference to this object, then finalize should be called and close the connection at a point of time automaticaly, but it is considered bad practice to rely on this behaviour.

And yes, connections are closed in a finally block by calling the close method, but since Java 7 there are better ways to do that. Please look at this: Closing Database Connections in Java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM