[英]Is this garbage-collected or not?
Here is some code: 这是一些代码:
public class A {
private volatile B b;
public void methodC() {
b.doSomething();
}
public void setB(B newB) {
this.b = newB;
}
}
'Thread 1' is executing b.doSomething() by executing methodC(). 'Thread 1'通过执行methodC()执行b.doSomething()。
At the same time 'thread 2' set a new B object into 'b'. 同时'线程2'将新的B对象设置为'b'。
My question is: 我的问题是:
Could the object previously refereced by 'b' be garbage-collected although doSomething() method on it is still executing? 先前由'b'引用的对象是否可以被垃圾收集,尽管它上面的doSomething()方法仍在执行?
No, because in order to call a member function you need to have a reference to the object. 不,因为要调用成员函数,您需要引用该对象。 Therefore the thread which is calling
b.doSomething()
will be holding a reference thus preventing garbage collection. 因此,调用
b.doSomething()
的线程将持有一个引用,从而防止垃圾回收。
Although check Jon Harrop's answer below for a situation when b
could be GC
'd. 虽然检查Jon Harrop的答案如下,因为
b
可能是GC
的情况。
Could the object previously refereced by 'b' be garbage-collected although doSomething() method on it is still executing?
先前由'b'引用的对象是否可以被垃圾收集,尽管它上面的doSomething()方法仍在执行?
Yes, the object previously refereced by 'b' might be garbage-collected even though the doSomething()
method on it is still executing. 是的,先前由'b'引用的对象可能是垃圾收集的,即使它上面的
doSomething()
方法仍在执行。
You might expect this
to be reachable while one of its methods is being executed because methods are implicitly passed the this
pointer and you might assume that it is always spilled to the stack. 你可能认为
this
在执行它的方法之一,因为方法是隐式传递的是可以到达this
指针,你可能认为它总是溢出到堆栈。 However, many optimizations can alter this and remove this
from the set of global roots seen by the GC. 然而,许多优化可以改变这一点,并删除
this
从一组由GC看到全球根。
For example, if the body of the doSomething
method ends with code that does not require this
and the method is inlined then this
might not be spilled from a register to the stack or its stack slot might be overwritten. 例如,如果
doSomething
方法的主体以不需要this
代码的代码结束,并且该方法被内联,那么this
可能不会从寄存器溢出到堆栈或其堆栈槽可能被覆盖。 In either case, the GC will no longer see this
even though execution is still inside doSomething
and, therefore, this
might be garbage collected. 在任何一种情况下,即使执行仍在
doSomething
,GC也不会再看到this
,因此, this
可能是垃圾回收。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.