Test t = new Test();对于这一句,t 保存在栈里,而 new Test()在堆中开辟空间,保存在堆中。 而t指向堆中的new出来的Test对象。继续向下:t=null; 则表示t不再指向任何具体对象。 此时在堆中new 出来的Test就没有引用了,可以被垃圾回收了。下面一段代码举个例子,在调用System.gc(),被回收的对象会调用finalize()方法。 准备被回收的对象: public class TestObj { String s = null; TestObj(String s) { this.s = s; System.out.println("new TestObj( " + s + ")"); } public void finalize() { System.out.println("TestObj.finalize( " + s + "), collect TestObj Object!"); } }测试对象何时被回收! public class GBCollection { public static void main(String args[]) { TestObj item = new TestObj("GB"); System.out.println("invoke System.gc()!"); System.gc(); int i = 5; while (i-- > 0) { try{ Thread.sleep(1000); System.out.println("go on running."); } catch(Exception e){
} } } }测试结果: new TestObj( GB) invoke System.gc()! go on running. go on running. go on running. go on running. go on running. after item = null; invoke System.gc() again! TestObj.finalize( GB), collect TestObj Object! go on running. go on running. go on running. go on running. go on running. go on running.
Test t=new Test();
t=null;这里的t=null表示什么意思呢? 是不是说把t所指向的内存释放掉?
null就是空 不指向任何内存空间
3楼的头像是 小龙女彤彤?
据说,据说一个对象所有引用都置空了或者说,已经没有引用了,GC可以回收该内存空间,不过,不一定是立即回收
Test t = new Test();对于这一句,t 保存在栈里,而 new Test()在堆中开辟空间,保存在堆中。
而t指向堆中的new出来的Test对象。继续向下:t=null;
则表示t不再指向任何具体对象。
此时在堆中new 出来的Test就没有引用了,可以被垃圾回收了。下面一段代码举个例子,在调用System.gc(),被回收的对象会调用finalize()方法。
准备被回收的对象:
public class TestObj {
String s = null; TestObj(String s) {
this.s = s;
System.out.println("new TestObj( " + s + ")");
} public void finalize() {
System.out.println("TestObj.finalize( " + s + "), collect TestObj Object!");
}
}测试对象何时被回收!
public class GBCollection {
public static void main(String args[]) {
TestObj item = new TestObj("GB");
System.out.println("invoke System.gc()!");
System.gc();
int i = 5;
while (i-- > 0) {
try{
Thread.sleep(1000);
System.out.println("go on running.");
}
catch(Exception e){
}
}
System.out.println("after item = null;\n invoke System.gc() again!");
item = null;
System.gc();
while (i++ < 5) {
try{
Thread.sleep(1000);
System.out.println("go on running.");
}
catch(Exception e){
}
}
}
}测试结果:
new TestObj( GB)
invoke System.gc()!
go on running.
go on running.
go on running.
go on running.
go on running.
after item = null;
invoke System.gc() again!
TestObj.finalize( GB), collect TestObj Object!
go on running.
go on running.
go on running.
go on running.
go on running.
go on running.
t=new String("someString");
s=t;
t=null;
但是如果小t和小s各自用一个绳子拿着同一个气球~如果t=null 就相当于用剪刀把绳剪断了 t小朋友手里只拿了个绳,
但是小s绳子没断,所以气球还没变成垃圾~
垃圾回收嘛,即没有对象指向它了,垃圾回收器发现之后,在合理的时间里就会对其处理
在类GBCollection中item=null,如果去掉这句,为什么系统运行没有执行item对象的finalize()方法呢,按道理来说,程序运行完,所有对象都将被JVM自动回收啊,也就会调用到被回收对象的finalize()方法,但是我测试了,没有调用被重写的finalize()方法。
不知道是为什么???
对象创建详见http://topic.csdn.net/u/20081120/17/54906067-d0c0-470e-b123-cf1fca9c4a28.html