bharal
bharal

Reputation: 16194

finalizer guardian didn't run

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.

Upvotes: 0

Views: 62

Answers (2)

Mohan Raj
Mohan Raj

Reputation: 1132

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.

Upvotes: 0

Vlad
Vlad

Reputation: 10780

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

Upvotes: 1

Related Questions