原问题链接为:http://topic.csdn.net/u/20071228/11/79119d03-4fd1-4a27-b394-78ca1258b400.html由于原问题已关闭,所以新开一个帖子讨论。简单描述如下:发帖人:microsealkey 其实我这儿的问题是通常性的讲,并非是专门针对联接的。 就是在对象生命周期结束的时候,需要关闭所有打开资源,为了确保所有资源关闭(即使发生异常也要尽可能关闭所有资源),所以必须一次一次的try...finally 其实我这段代码是放在finalize()里面的:在对象生命周期结束的时候,确保关闭所有资源(数据库,文件等等)。 所以应该没有什么好分解的吧?这儿仅仅就是关闭资源的代码。
public void close() throws IOException, SQLException {
try {
saveDisk();
} finally {
try {
mDelLogStmt.close();
} finally {
try {
mUpdateWorkingStmt.close();
} finally {
try {
mDataStmt.close();
} finally {
try {
mShareSearcher.destroyShareObj();
} finally {
try {
mw.close();
} finally {
try {
mMemDir.close();
} finally {
try {
mDiskDir.close();
} finally {
mDiskDir= null;
mMemDir= null;
mw= null;
mShareSearcher= null;
mDataStmt= null;
mUpdateWorkingStmt= null;
mDelLogStmt= null;
}
}
}
}
}
}
}
}
解决方案来自《Java解惑》(美 Joshua Bloch Neal Gafter著,陈昊鹏译,人民邮电出版社出版)P88~P89第41个谜题。
这种代码重构方式是从5.0开始的,利用的是Closeable接口
具体模式如下: try
{
//some code
}
finally
{
closeIgnoringException(in);
closeIgnoringException(out);
}
}
private static void closeIgnoringException(Closeable c)
{
if( c!= null )
{
try
{
c.close();
}
catch(IOException ex)
{
//There is nothing we can do if close fails
}
}
}
public void close() throws IOException, SQLException {
try {
saveDisk();
} finally {
try {
mDelLogStmt.close();
} finally {
try {
mUpdateWorkingStmt.close();
} finally {
try {
mDataStmt.close();
} finally {
try {
mShareSearcher.destroyShareObj();
} finally {
try {
mw.close();
} finally {
try {
mMemDir.close();
} finally {
try {
mDiskDir.close();
} finally {
mDiskDir= null;
mMemDir= null;
mw= null;
mShareSearcher= null;
mDataStmt= null;
mUpdateWorkingStmt= null;
mDelLogStmt= null;
}
}
}
}
}
}
}
}
解决方案来自《Java解惑》(美 Joshua Bloch Neal Gafter著,陈昊鹏译,人民邮电出版社出版)P88~P89第41个谜题。
这种代码重构方式是从5.0开始的,利用的是Closeable接口
具体模式如下: try
{
//some code
}
finally
{
closeIgnoringException(in);
closeIgnoringException(out);
}
}
private static void closeIgnoringException(Closeable c)
{
if( c!= null )
{
try
{
c.close();
}
catch(IOException ex)
{
//There is nothing we can do if close fails
}
}
}
try {
saveDisk();
} finally {
try {
mDelLogStmt.close();
} finally {
try {
mUpdateWorkingStmt.close();
} finally {
try {
mDataStmt.close();
} finally {
try {
mShareSearcher.destroyShareObj();
} finally {
try {
mw.close();
} finally {
try {
mMemDir.close();
} finally {
try {
mDiskDir.close();
} finally {
mDiskDir= null;
mMemDir= null;
mw= null;
mShareSearcher= null;
mDataStmt= null;
mUpdateWorkingStmt= null;
mDelLogStmt= null;
}
}
}
}
}
}
}
} try
{
//some code
}
finally
{
closeIgnoringException(in);
closeIgnoringException(out);
}
}
private static void closeIgnoringException(Closeable c)
{
if( c!= null )
{
try
{
c.close();
}
catch(IOException ex)
{
//There is nothing we can do if close fails
}
}
}