Java - 可以对正在执行方法的对象进行垃圾收集吗?

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)