Finalize () not getting called

Why is finalize()

n't it called here. The code compiled and ran successfully, but there was no exit.

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();
    }

}

      

+3


source to share


4 answers


Your call System.gc();

is irrelevant, as your instance Temp

has a reference ( obj

), so it is not eligible for garbage collection.



Even if it is eligible for garbage collection, the call System.gc();

does not necessarily collect all objects that do not have a reference to them immediately.

+6


source


It just so happens that im reading Effective Java

STEP 7: AVOID FINALIZERS

Finalizers are unpredictable, often dangerous, and generally unnecessary. -efficient Java (p. 50)

another from pdf.



Don't be tempted by the System.gc and System.runFinalization methods. They can increase the chances of finalizers being executed, but they don't guarantee 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 deprecated by [ThreadStop].

based on this using System.gc will only increase the chances of finalizers to be executed and it is important to use it does not guarantee it will trigger garbage collection but only suggests jvm.

other.

Not only does the language specification not guarantee that finalizers will be executed promptly; he does not guarantee that they will be executed in CHAPTER 2 CREATING AND DESTROYING OBJECTS 28 all. It is possible, even possible, that the program terminates without executing finalizers on some objects that are no longer reachable

+2


source


add obj = null;

to make the reference null, then the finalize method will be called. Thsi again is not a guaranteed behavior, 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.

      

+1


source


when creating an object called by the constructor but not the finalize () method, so you need to pass the function from the obj instance and here System.gc (); makes no difference or is called the finalize () method;

0


source







All Articles