Closing database connection to avoid memory leak

2020-05-04 11:15发布

问题:

Follow up question to Closing Database Connections in Java

Connection conn = DriverManager.getConnection(
     "jdbc:somejdbcvendor:other data needed by some jdbc vendor",
     "myLogin",
     "myPassword" );

Statement stmt = conn.createStatement();
try {
    stmt.executeUpdate( "INSERT INTO MyTable( name ) VALUES ( 'my name' ) " );
} finally {
    //It's important to close the statement when you are done with it
    stmt.close();
}
conn.close();

I know that conn.close() is necessary but do not know why. Won't the garbage collector free the connection object (and with it release every handler stored in it that points to the database), once the method call is over?

回答1:

Won't the garbage collector free the connection object (and with it release every handler stored in it that points to the database), once the method call is over?

It doesn't. The JDBC driver retains a reference to to connection, so it is not cleaned up unless you can close().

BTW creating a database connection is very expensive, so you will want to recycle your connections where possible.



回答2:

You're trusting that you're the only one who has references to the Connection. The driver probably keeps track of them, and it won't let go of a connection that hasn't been closed. That's why you always need to close all more complicated resources (connections, streams, etc.).