把Connection设置null,有必要吗?设置Object为null是否释放资源?两个问题一并问

applebomb 2006-03-16 11:51:45
释放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有何意义呢?
...全文
117 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
applebomb 2006-03-31
  • 打赏
  • 举报
回复
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视为该类不再被引用,这个跟一个变量重新赋值的效果一样。
crazycy 2006-03-17
  • 打赏
  • 举报
回复
当对象不被引用时就会被回收,这个过程是由GC来检查的,而不是设置成null就决定回收与否,毕竟设置成null后,后边有可能被再赋值再次使用的
fashchina 2006-03-17
  • 打赏
  • 举报
回复
设置为null 是为了垃圾回车更好的回收
Albert_1030 2006-03-17
  • 打赏
  • 举报
回复
gc销毁前会查看,引用是不是指向了无效的空间。
Albert_1030 2006-03-17
  • 打赏
  • 举报
回复
en en
horseyet 2006-03-17
  • 打赏
  • 举报
回复
如果不设置为null;就算调用了gc也不会销毁对象的

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧