0

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.

Community
  • 1
  • 1
bharal
  • 15,461
  • 36
  • 117
  • 195
  • Is some information missing here? All I (and Java probably) can see is private class member that is a custom object containing one method. Why would it be run? – Deltharis Nov 18 '14 at 10:19
  • 1
    I think he is talking about finalize... but anyway from what I can find there are more questions about this http://stackoverflow.com/questions/2506488/when-is-the-finalize-method-called-in-java – João Costa Nov 18 '14 at 10:20
  • 1
    Don't rely on finalizers - http://www.informit.com/articles/article.aspx?p=1216151&seqNum=7 – Eran Nov 18 '14 at 10:23
  • In Java, the try-finally block is generally used for this purpose. – Naman Gala Nov 18 '14 at 10:30

2 Answers2

1

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

Vlad
  • 10,602
  • 2
  • 36
  • 38
  • program termination doesn't run gc ? that is something i didn't know – bharal Nov 18 '14 at 10:34
  • There is nothing in jls about running gc before programm exits. You can try to make a long running loop and wait for gc to run. – pomkine Nov 18 '14 at 10:57
0

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.

Mohan Raj
  • 1,104
  • 9
  • 17