Search code examples
javaobjectgarbage-collectionprogram-entry-point

Java - Can objects which are executing methods be garbage-collected?


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).


Solution

  • 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.