释放Connection的代码有的写法如下:
if(conn!=null&&!conn.isClosed()){ conn.close(); conn=null; }
是不是将conn对象设置为null就会销毁该对象或是加速释放呢?自己做了测试代码:public class Test { /**
*
*/
public Test() {
super();
} /**
* @param args
*/
public static void main(String[] args) {
aa();
} @Override
protected void finalize() throws Throwable {
// TODO 自动生成方法存根
super.finalize();
System.out.println("freed");
}
private static void aa()
{
Test tt = new Test();
System.out.println(tt.getClass().getName());
tt = null;
//System.gc();
}
}实际上只有执行System.gc()才销毁了对象,那设置Object=null有何意义呢?
if(conn!=null&&!conn.isClosed()){ conn.close(); conn=null; }
是不是将conn对象设置为null就会销毁该对象或是加速释放呢?自己做了测试代码:public class Test { /**
*
*/
public Test() {
super();
} /**
* @param args
*/
public static void main(String[] args) {
aa();
} @Override
protected void finalize() throws Throwable {
// TODO 自动生成方法存根
super.finalize();
System.out.println("freed");
}
private static void aa()
{
Test tt = new Test();
System.out.println(tt.getClass().getName());
tt = null;
//System.gc();
}
}实际上只有执行System.gc()才销毁了对象,那设置Object=null有何意义呢?
/**
*
*/
public Test(int i) {
super();
System.out.println("Happy Birthday.");
this.i = i;
} /**
* @param args
*/
public static void main(String[] args) {
aa();
} @Override
protected void finalize() throws Throwable {
// TODO 自动生成方法存根
super.finalize();
System.out.println("freed." + i);
} private static void doit(int i)
{
Test tt = new Test(1);
System.out.println(tt.getClass().getName() + i);
//tt = null;
}
private void doit()
{
Test tt = new Test(1);
System.out.println(tt.getClass().getName() + i);
//tt = null;
} private static void aa() {
//doit(23); //<-- 放在这里则会释放
{
Test tt = new Test(1); //<-- 这个释放不了
System.out.println(tt.getClass().getName());
//tt = null;
tt = new Test(2);
}
System.gc();
}
}答案似乎是这样的:
类实例设置为null视为该类不再被引用,这个跟一个变量重新赋值的效果一样。