问题描述
在 Java 中,我没有多想就做了以下事情:
In Java, I've done things like the following without thinking much about it:
public class Main {
public void run() {
// ...
}
public static void main(String[] args) {
new Main().run();
}
}
但是,最近我开始不确定这样做是否安全.毕竟, Main
对象在创建之后就没有引用了(嗯,有 this
引用,但这算不算?),所以看起来有一个垃圾收集器可能会在对象执行过程中删除对象的危险.所以也许 main
方法应该是这样的:
However, recently I've become unsure as to whether doing that is safe. After all, there is no reference to the Main
object after it's created (well, there is the this
reference, but does that count?), so it looks like there's a danger that the garbage collector might delete the object while it's in the middle of executing something. So perhaps the main
method should look like this:
public static void main(String[] args) {
Main m = new Main();
m.run();
}
现在,我很确定第一个版本可以正常工作,而且我从来没有遇到过任何问题,但我想知道在所有情况下这样做是否安全(不仅在特定的 JVM 中,而且最好根据语言规范对此类情况的说明).
Now, I'm pretty sure that the first version works and I've never had any problems with it, but I'd like to know if it's safe to do in all cases (not only in a specific JVM, but preferably according to what the language specification says about such cases).
推荐答案
如果正在执行一个对象方法,则意味着有人拥有该引用.所以不,在执行方法时不能对对象进行 GC.
If an object method is being executed, it means someone is in possession of that reference. So no, an object can't be GC'd while a method is being executed.
这篇关于Java - 可以对正在执行方法的对象进行垃圾收集吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!