0
class MyObj {
    public void print() {
        System.out.println("Hello!");
    }
    @Override
    protected void finalize() throws Throwable {
        System.out.println("MyObj Destroyed");
        super.finalize();
    }

    public static void main(String... args) {
        MyObj obj = new MyObj();
        obj.print();
        for (int i = 0; i < 10000000; i++) {
            byte[] b = new byte[100];
        }
        System.out.println("done");
    }
}

Hello!
MyObj Destroyed
done

but when I change the main method to this

public static void main(String... args) {
    MyObj obj = new MyObj();
    obj.print();
    for (int i = 0; i < 10000000; i++) { 
        byte[] b = new byte[100]; //just create objects to force garbage collector to run
    }
    obj.print(); //call print here
    System.out.println("done");
}

Hello!
Hello!
done

Does Java automatically set strong references to null on their last use?

John E.
  • 418
  • 2
  • 10
  • When it is no longer reachable, when you copy the call to after your `for` loop; it's reachable after the `for` loop (and will thus not be eligible for `gc`). – Elliott Frisch Dec 31 '15 at 03:21
  • A *reference* is *never* ready for garbage collection, but an *object* is, when it has no live references. Java never automatically sets anything to null after initialization. – user207421 Dec 31 '15 at 04:33

1 Answers1

-1

An object is eligible for garbage collection when it is no longer reachable.
Just because an object is eligible for garbage collection doesn’t mean it will be collected.

Magnus
  • 7,952
  • 2
  • 26
  • 52
  • 1
    Calling `System.gc()` won't do anything since there isn't much memory allocated. I tried it already. It's up to the garbage collector to run if you call it. – John E. Dec 31 '15 at 03:26
  • Calling System.gc() is merely a suggestion to the garbage collector to make it's rounds. There is simply no way to force or trigger garbage collection in any way. If a program is very small then there is a very real chance that it will never run at all no matter how many times you make that call. – Julian Dec 31 '15 at 03:55
  • Ive removed the part about System.gc() – Magnus Dec 31 '15 at 03:57