释放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有何意义呢?

解决方案 »

  1.   

    如果不设置为null;就算调用了gc也不会销毁对象的
      

  2.   

    设置为null 是为了垃圾回车更好的回收
      

  3.   

    当对象不被引用时就会被回收,这个过程是由GC来检查的,而不是设置成null就决定回收与否,毕竟设置成null后,后边有可能被再赋值再次使用的
      

  4.   

    public class Test { private int i;
    /**
     * 
     */
    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视为该类不再被引用,这个跟一个变量重新赋值的效果一样。