Newbie - finalization() question

I don't understand how finalize works.  I have two scripts that contain a class with a finalize() function included.  The first one does not execute the finalize function, whereas the second does.  To me, it should be executed for both scripts.  Why is that?

The only difference between the two scripts is markewd with the comment "Different"

Script #1

class CloseIt {

  boolean ib_open;

  CloseIt() {
    SetOpen(true);
  }

  void SetOpen(boolean ab_open) {
    if (ab_open) {
      System.out.println("Object open.");
    }
    else {
      System.out.println("Object closed.");
    }

    ib_open = ab_open;
  }

  public void finalize() {
    if (ib_open) {
      System.out.println("Object not closed");
    }
  }

}

public class Exercise12 {

  public static void main(String[] args) {

    CloseIt now = new CloseIt();
    now.SetOpen(false);

    CloseIt later = new CloseIt();     //Different

    System.gc();

  }
}

================================================

Script #2

class CloseIt {

  boolean ib_open;

  CloseIt() {
    SetOpen(true);
  }

  void SetOpen(boolean ab_open) {
    if (ab_open) {
      System.out.println("Object open.");
    }
    else {
      System.out.println("Object closed.");
    }

    ib_open = ab_open;
  }

  public void finalize() {
    if (ib_open) {
      System.out.println("Object not closed");
    }
  }

}

public class Exercise12 {

  public static void main(String[] args) {

    CloseIt now = new CloseIt();
    now.SetOpen(false);

    new CloseIt();    //Different

    System.gc();

  }
}


joos01Asked:
Who is Participating?
 
Jim CakalicSenior Developer/ArchitectCommented:
In the second example you don't hold a reference to the second CloseIt object so when gc is invoked that object can be garbage collected. In the first example there is a reference held to both the now and later CloseIt objects so they are not candidates for garbage collection when gc is invoked.

Regards,
Jim Cakalic
0
 
joos01Author Commented:
Thanks Jim!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.