在下面的代码中,假设 amethod
已被调用.myObject
最初引用的对象在哪一点/哪一行符合垃圾回收条件?
In the code below, given that amethod
has been called. At what point/line is the Object originally referenced by myObject
, eligible for Garbage Collection?
class Test {
private Object classObject;
public void amethod() {
Object myObject = new Object();
classObject = myObject;
myObject = null;
}
}
如果 classObject
或 amethod
具有 public、protected、default 或 static 的访问修饰符,它会影响对象符合垃圾收集条件的点吗?如果有,会受到怎样的影响?
And if classObject
or amethod
had an access modifier of public, protected, default or static, would it affect what point the Object is eligible for Garbage Collection? If so, how would it be affected?
classObject = myObject;
将被优化出来并且 myObject = null;
是它有资格进行垃圾收集的点.classObject = myObject;
would be optimized out and myObject = null;
is the point it is eligible for Garbage Collection.对象将不会成为垃圾回收的候选对象,直到对它的所有引用都被丢弃.Java 对象是通过引用分配的,所以当你有
The object will not become a candidate for garbage collection until all references to it are discarded. Java objects are assigned by reference so when you had
classObject = myObject;
您为堆上的同一对象分配了另一个引用.所以这一行
You assigned another reference to the same object on the heap. So this line
myObject = null;
只去掉一个引用.要使 myObject
成为垃圾回收的候选对象,您必须拥有
Only gets rid of one reference. To make myObject
a candidate for garbage collection, you have to have
classObject = null;
这篇关于对象何时有资格进行垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!