finalizer guardian didn't run

64 views Asked by At

My finalizer guardian failed to run by the time my program exited.

Here he is:

public class SomeClass implements SomeInterface {

    ... setup the PrintWriter os somewhere here

    /** oh, i guess i wanted to try out finalizer guardians here. */
    @SuppressWarnings("unused")
    private final Object finalizerGuardian = new Object(){
        protected void finalize(){
            try {
                //actually, i cannot know if it was closed or not. 
                System.out.println("connection wasn't closed - it needs to be!");
                os.flush();
                os.close();
            } catch (Exception se){
                System.out.println("some sort of exception occurred? Weird");
            }
        }
    };

    ...

}

What did i do wrong? I thought finalizerGuardians were guaranteed to run? Or is that not the case? The PrintWriter os is definitely not flushed or closed otherwise by the time this program terminates.

2

There are 2 answers

2
Vlad On

finalize() is called during garbage collection, your program probably exists before this happens.

0
Mohan Raj On

Finalizer thread is part of Garbage Collection(GC). Although indeed part of GC it was not guaranteed by GC when it will run. Finalize method moves object to the finalizer objects queue where finalizer threads clears the objects present in the queue when it run.