简体   繁体   中英

How does java GC work if there is no reference variable?

I know java GC can destroy an object on the heap if the reference variable that points to the object is manually set to null or set to point to another object:

TestObject test = new TestObject();
test.dosomething();
test = null;

My question is that if I did not give that object a name (reference variable) when I created it, how do I free the memory that object occupies after I'm done with the object:

(new TestObject()).dosomething();

Will this object live on the heap forever before the program ends?

After you create the object with new and call the method dosomething() on it there are no references left to it so it becomes eligible for garbage collection.

Even if you create two objects which point to each other with references and they no longer have a connection to the root reference they will become eligible to gc as well (the jvm can detect this circular reference without root connection).

So to answer your question: No that object in your second example will be gc-ed after you call dosomething on it.

Just a note: In practice you don't need to null your references (I actually nearly never do it) it is enough if you keep them in local scope so when you leave it the local variables get cleaned up.

I'm going to explain this through byte code. First thing to note is that while a reachable reference exists to an object, that object cannot be collected. A important aspect of this is that if a reference value is on the stack in a method's stack frame, the object being referenced is accessible. It therefore cannot be garbage collected.

Compile the following program

public class Example {
    public static void main(String[]args) {
        new Example().sayHello();
    }

    public void sayHello() {}
}

Running javap -c Example will give you something like

  public static void main(java.lang.String[]);
    Code:
      stack=2, locals=1, args_size=1
         0: new           #2                  // class Example
         3: dup
         4: invokespecial #3                  // Method "<init>":()V
         7: invokevirtual #4                  // Method sayHello:()V
        10: return

A index 0 , the new byte code instruction, creates a new object and pushes the reference to that object onto the stack. The dup instruction copies that value and pushes it on top of the stack. So you now have two references to that object. invokespecial uses one, invokevirtual uses the other (they pop the reference value they use). Once that is done, there are no more references to the object and it can be garbage collected.

For reference, here are the byte code instructions .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM