Java - 可以执行方法的对象是垃圾回收吗? [英] Java - Can objects which are executing methods be garbage-collected?
问题描述
public class Main {
public void run(){
// ...
}
public static void(String [] args){
new main()的运行();
}
}
然而,最近我不确定是否这样做是安全的。毕竟,在创建它之后,没有对 Main
对象的引用(当然, this
引用,但是这是否值得?),所以看起来像垃圾收集器可能会在执行某些事情的时候删除对象。因此,也许 main
方法应该如下所示:
public static void main(String [] args){
Main m = new Main();
m.run();
}
现在,我很确定第一个版本可以正常工作,从来没有任何问题,但我想知道在所有情况下是否安全(不仅在特定的JVM中,但最好根据语言规范对这种情况的描述)。
如果一个对象方法正在执行,这意味着有人拥有该引用。所以不行,当一个方法正在执行时,一个对象不能被GC'd。
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();
}
}
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();
}
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).
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 - 可以执行方法的对象是垃圾回收吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!