Java - Can objects which are executing methods be garbage-collected?(Java - 可以对正在执行方法的对象进行垃圾收集吗?)
问题描述
在 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 - 可以对正在执行方法的对象进行垃圾收集吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java - 可以对正在执行方法的对象进行垃圾收集吗?


基础教程推荐
- 降序排序:Java Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01