daft300punk
daft300punk

Reputation: 169

finalize() not getting called

Why is finalize() not being called here. The code compiled and ran successfully but there wasn't any output.

package temp;

public class Temp {

    int i;

    Temp(int j) {
        i = j;
    }

    public void finalize() {
        if (i == 10) {
            System.out.println("Finalize called.");
        }
    }

    public static void main(String[] args) {
        Temp obj = new Temp(10);
        System.gc();
    }

}

Upvotes: 3

Views: 824

Answers (4)

Secondo
Secondo

Reputation: 451

It so happen that im reading Effective Java

ITEM 7: AVOID FINALIZERS

Finalizers are unpredictable, often dangerous, and generally unnecessary. -Effective Java (page 50)

another one from pdf.

Don’t be seduced by the methods System.gc and System.runFinalization . They may increase the odds of finalizers ge tting executed, but they don’t guaran- tee it. The only methods that claim to guarantee finalization are System.runFi- nalizersOnExit and its evil twin, Runtime.runFinalizersOnExit . These methods are fatally flawed and have been deprecated [ThreadStop].

based on this using System.gc will only increase the odds of finalizers getting executed and importantly using it will not guarantee that it will run the Garbage Collection, it is only suggesting to the jvm.

another one.

Not only does the language specification provide no guarantee that finalizers will get executed promptly; it provides no guarantee that they’ll get executed at CHAPTER 2 CREATING AND DESTROYING OBJECTS 28 all. It is entirely possible, even likely, that a program terminates without executing finalizers on some objects that are no longer reachable

Upvotes: 2

Ankur Singhal
Ankur Singhal

Reputation: 26077

add obj = null; to make reference null, then your finalize method will be called. Thsi is again not a guranteed behaviour, for me 1-2 times i was able to call it out of 5 times.

 public static void main(String[] args) {
        Temp obj = new Temp(10);
        obj  = null;
        System.gc();
    }

Output

hi10
Finalize called.

Upvotes: 0

Nishant Singhal
Nishant Singhal

Reputation: 21

while creating an object the constructor is called but not the finalise() method so you need to refer the function from instance obj and here System.gc(); has not made any difference or called the method finalize();

Upvotes: 0

Eran
Eran

Reputation: 394156

Your call to System.gc(); makes no difference, since your Temp instance has a reference (obj) so it's not eligible for garbage collection.

Even if it was eligible for garbage collection, calling System.gc(); doesn't necessarily collect all the objects that have no reference to them immediately.

Upvotes: 6

Related Questions