关于JDBC的close问题

     因为过去一直在Hibernate上开发程序,对于JDBC的直接应用相对较少。最近在编写一个从1000万的表中提取数据为全文检索做索引的程序时出现了内存益处(OutOfMemoryError)问题,经过反复排查发现问题的根源在于没有及时地close数据库的相关资源。在我的程序中,一批一批地从数据库中提取数据进行索引。一开始,为了减少不必要的开销,我只建立了一个Connection,每次将数据加载到内存时都使用这一个Connection.尽管我注意到了在每个批次执行结束后,把不必要的对象引用置空,但这并没有阻止内存益处的问题。事实上,查询的数据集并不只是由DateSet一个引用来指向的,ResultSet从属于Statement,Statement又从属于Connection,这样,单纯地把ResultSet或Statement置空并不会使它们的数据集合被GC回收。(而对于Connection来说,它被置空成为垃圾时,JVM会调用它的close方法来释放资源,但这不是好的编程习惯,我们还是应该显式地调用close来完成这一工作)。因此,我的程序的问题在于:使用一个Connection并在最后关闭它并不是问题,问题在于,在循环过程中间,没有释放Statement和ResultSet!这里所说的“释放”,是指调用它们的close方法,而不是把它们置空!或者另一个方法就是每次循环打开一个Connection,并在循环结束时关闭它。
     对于ResultSet,Statement,Connection的关闭有这样一种关系:关闭一个Statement会把它的所有的ResultSet关闭掉,关闭一个Connection会把它的所有的Statement关闭掉。以下摘自《Database Programming with JDBC and JAVA》3.3.3一节:
     The Connection, Statement, and ResultSet classes all have close( ). A given JDBC
implementation may or may not require you to close these objects before reuse. But some might
require it, since they are likely to hold precious database resources. It is therefore always a good
idea to close any instance of these objects when you are done with them. It is useful to remember
that closing a Connection implicitly closes all Statement instances associated with the
Connection.[3] Similarly, closing a Statement implicitly closes ResultSet instances associated
with it. If you do manage to close a Connection before committing with auto-commit off, any
uncommitted transactions will be lost.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Laurence 

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值