[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 200
  • Last Modified:

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

  }
}


0
joos01
Asked:
joos01
1 Solution
 
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

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now