forcing a finalize method to run


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: forcing a finalize method to run

  1. #1
    new2java Guest

    forcing a finalize method to run


    In the proceeding code I want to force the finalize method to run for 'a'
    (a reference of Type 'A' that is pointing to and object of type 'B') when
    it is assigned a null. I want to verify that the finalize method for class
    B will run and that the output will be "class B". As it stands, there is
    no output when the code is run.

    What am I doing wrong?

    class A {
    int x;
    protected void finalize () throws Throwable {System.out.println(" class
    A");}
    }


    class B extends A{
    int x;
    protected void finalize () throws Throwable {System.out.println(" class
    B");}
    public static void main (String [] args) {
    A a = new B();
    a = null;

    System.runFinalization();
    System.gc();
    }
    }


  2. #2
    Christian Yungk Guest

    Re: forcing a finalize method to run


    Hello,

    My guess is that you are running into problems with it not running the finalization
    because you are only "suggesting" to the JVM to run the finalizer and garbage
    collection. System.gc() and I believe System.runFinalization() are both
    really just suggestions to the JVM. The JVM still determines when it wants
    to actually peform these actions. Try running the same code and then generating
    a lot of bogus object references to eat up your allocated memory. That way
    the garbage collection should run.


    "new2java" <mswirt@aol.com> wrote:
    >
    >In the proceeding code I want to force the finalize method to run for 'a'
    >(a reference of Type 'A' that is pointing to and object of type 'B') when
    >it is assigned a null. I want to verify that the finalize method for class
    >B will run and that the output will be "class B". As it stands, there is
    >no output when the code is run.
    >
    >What am I doing wrong?
    >
    >class A {
    > int x;
    > protected void finalize () throws Throwable {System.out.println(" class
    >A");}
    >}
    >
    >
    >class B extends A{
    > int x;
    > protected void finalize () throws Throwable {System.out.println(" class
    >B");}
    > public static void main (String [] args) {
    > A a = new B();
    > a = null;
    >
    > System.runFinalization();
    > System.gc();
    > }
    >}
    >


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center