您的位置:首页 > 其它

关于statement.close和connection.close 备忘(上)

2011-06-27 17:56 246 查看
很多人都会有这个疑问。在回收数据库连接资源的时候,大家一般都用connection.close() ,那么在这个过程中其持有的statements和results是否被清理或标记为无效了呢?我们又应该用哪种方式来释放数据库资源呢?

这个既和你使用数据库连接的方式有关,也和驱动有关,也就是和你的jdbc/odbc…… Driver有关。

我们来看看mysql-connector的源代码:

v5.0.7 Connection.java

public void close() throws SQLException { 这里去掉了3.1.12版本的同步
realClose(true, true, false, null);
}

realClose中做了很多事,包括

closeAllOpenStatements();

this.io.quit(); 注意这里关闭了io

this.io.forceClose(); 注意这里关闭了io

其中closeAllOpenStatements()中会调用connection中所有stmt的realClose(false, true);

最后还有:

this.openStatements = null;
this.io = null;

ProfileEventSink.removeInstance(this); // 3.1.12版本没有这句
this.isClosed = true;

v5.0.7 Statement.java

public void close() throws SQLException {
realClose(true, true);
}
在realClose中,

this.closeAllOpenResults(); 关闭了所有Results

对connection做了一些简单清理工作:

if (this.connection != null) {
if (this.maxRowsChanged) {
this.connection.unsetMaxRows(this);
}

if (!this.connection.getDontTrackOpenResources()) {
this.connection.unregisterStatement(this);
}
}

最后还有this.connection = null;

那么可以看出,最重要的地方在于 connection.close 关闭了connection的io 而statement没有关闭io 只是将connection设为null。

可以说connection.close () 关闭得更为彻底。

但是这样关闭不一定是必要的。 事实上我们在使用过程中不是一定要关得这么彻底,比如用数据库连接池的时候,在数据库操作完成后,完全可以用statement.close() 。这样该释放的都释放了,但是连接还在那里 ,下次用的时候也不用重新做io,这样想必效率上要高些。

另外在使用过程中必须具体应用具体分析,还必须仔细看看jdbc的代码。毕竟每个Driver或多或少有不同之处。

我在每分钟万级(不到10w)访问的情况下应用过statement.close(),没发现有任何内存泄露问题。

下一步需要做做比较,看看在效率和资源上的具体差别。

by zwonder 201106271756
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: