🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Thread View: aus.computers.java
13 messages
13 total messages Started by DavidL Thu, 12 Oct 2000 00:00
How to cleanup when a class is destroyed ?
#430
Author: DavidL
Date: Thu, 12 Oct 2000 00:00
51 lines
1990 bytes
Hi all,

I have come to java from C++, where when you want to cleanup when a class is
destroyed you would write a destructor.

I am having trouble getting the same functionailty from java.

From what I have read, I understood that this was the function of the
"finalize" method.
However, I don't seem to be able to get it to work.

Take this example:

    ---------------------------------------------
    class    app
    {
        static public void    main (String args[])
        {
            class1 c = new class1();
        }
    }
    ---------------------------------------------
    class    class1
    {
        public    class1 ()
        {
            System.out.println ("class1()"):
        }

        protected void    finalize ()
        {
            System.out.println ("class1.finalize()");
        }
    }
    ---------------------------------------------

My expectation is that if I compile and run "app" I would see:

    class1()
    class1.finalize()

but instead I just see

    class1()

This tells me that the finalize method is not being run.

Am I missing something here ?

Ta
    DavidL
Re: How to cleanup when a class is destroyed ?
#432
Author: Stephen Oakes
Date: Thu, 12 Oct 2000 00:00
4 lines
821 bytes
In Java you let the garbage collector clean up.

--
Stephen Oakes
Re: How to cleanup when a class is destroyed ?
#433
Author: DavidL
Date: Thu, 12 Oct 2000 00:00
22 lines
1522 bytes
I agree Stephen.

But shouldn't the garbage collector cleanup when the application is
completed ?

I thought that when the app is completed, the garbage collector would clean
up the the instantiated class1, hence calling the finalize method.

If that isn't the case, how do you arrange for an instantiated class to
close ports it has opend etc, when the application is completed ?

This is puzzling !

"Stephen Oakes" <soakes1@bigpond.net.au> wrote in message
news:uDgF5.2142$wG1.4828@news-server.bigpond.net.au...
> In Java you let the garbage collector clean up.
>
> --
> Stephen Oakes
>
>
>
Re: How to cleanup when a class is destroyed ?
#434
Author: Benjamin Johnston
Date: Thu, 12 Oct 2000 00:00
32 lines
1791 bytes
> I agree Stephen.
>
> But shouldn't the garbage collector cleanup when the application is
> completed ?
>
> I thought that when the app is completed, the garbage collector would
clean
> up the the instantiated class1, hence calling the finalize method.
>
> If that isn't the case, how do you arrange for an instantiated class to
> close ports it has opend etc, when the application is completed ?
>
> This is puzzling !

Take a look at the JavaDocs for;
System.runFinalizersOnExit(boolean);

And
Object.finalize();


But, keep in mind that most of the time you'll find that you won't/shouldn't
need to do any finalization at all (its more of a C++ thing)...

To quote "Java 2 Performance and Idiom Guide";
For many resources (threads, files, sockets and so on) it will be usually be
completely obvious when they can be released or closed. The finalize method,
on the other hand, should be used as a last-ditch cleanup effort for
de-registration.

-Benjamin Johnston
s355171@student.uq.edu.au
Re: How to cleanup when a class is destroyed ?
#435
Author: DavidL
Date: Thu, 12 Oct 2000 00:00
33 lines
1775 bytes
Thanks Benjamin.

I will look at that now.

"Benjamin Johnston" <s355171@student.uq.edu.au> wrote in message
news:8s4972$43o$1@bunyip.cc.uq.edu.au...
> >
...snip...
>
> Take a look at the JavaDocs for;
> System.runFinalizersOnExit(boolean);
>
> And
> Object.finalize();
>
>
> But, keep in mind that most of the time you'll find that you
won't/shouldn't
> need to do any finalization at all (its more of a C++ thing)...
>
> To quote "Java 2 Performance and Idiom Guide";
> For many resources (threads, files, sockets and so on) it will be usually
be
> completely obvious when they can be released or closed. The finalize
method,
> on the other hand, should be used as a last-ditch cleanup effort for
> de-registration.
>
> -Benjamin Johnston
> s355171@student.uq.edu.au
>
>
>
Re: How to cleanup when a class is destroyed ?
#436
Author: Dwayne Conyers
Date: Thu, 12 Oct 2000 00:00
8 lines
899 bytes
It isn't necessary in Java.


--

Weekly Web-Design Articles
Now at Dwacon Software
http://www.dwacon.com/Software
Re: How to cleanup when a class is destroyed ?
#437
Author: DavidL
Date: Thu, 12 Oct 2000 00:00
47 lines
1855 bytes
But what if I have a class something like:

class    port
{
    int        port_num;

    public        port (int i)
    {
        port_num = i;
    }

    public void    open ()
    {
        OsOpenPort (i);
    }

    public void    close ()
    {
        OsClosePort (i);
    }
}

Assume that this class is accessing some hardware port via the OS, maybe a
serial port.

You would certainly like that port to be available after the application is
terminated.

How do I ensure that the close() method is called ?
It is unreasonable to expect that the application will always call the
close() method, especially if there is an error.

David L :-)


"Dwayne Conyers" <dwacon@anti-spam.theglobe.com> wrote in message
news:%rnF5.41125$td5.6548300@news1.rdc2.pa.home.com...
> It isn't necessary in Java.
>
>
> --
>
> Weekly Web-Design Articles
> Now at Dwacon Software
> http://www.dwacon.com/Software
>
>
Re: How to cleanup when a class is destroyed ?
#440
Author: DavidL
Date: Fri, 13 Oct 2000 00:00
64 lines
2611 bytes
Thanks Ross.

I probably need to be more precise with my questions, so they can't be
confused.

I am aware of the finalize method, but, unfortunately, haven't seen it work.

If I have a simple class like:

    class    class1
    {
        protected void    finalize ()
        {
            System.out.println ("finalize called");
        }
    }

and I instantiate an instance of this class in a simple command line app
like:

    class app
    {
        static void main (String args[])
        {
            class1 c = new class1 ();
        }
    }

then when that app runs I would expect the "finalize called" message to be
displayed, but it doesn't happen.

Maybe my JVM is broken ?

"Ross Vumbaca" <rossv@au.net.fl> wrote in message
news:39E708EC.4C33B23D@au.net.fl...
> Hi,
>
> DavidL wrote:
>
> > But what if I have a class something like:
>
> <Snip>
>
> People keep confusing your request with garbage collection, which Java
> does. There is a "finalize" method for Java objects, which is run when
> an object is trashed. Can't help much else though ;). The other post
> with the javadocs link will help you.
>
> Regards,
>
> Ross..
>
> --
> *TO E-MAIL ME: Reverse the order of the domain name in my e-mail
> address.*
>
> Ross Vumbaca, a 'poor' Uni student at USyd.edu.au
> http://www.fl.net.au/~rossv
>
> Running on an Amiga 3000 (030/25), ECS, 8Mb Fast, 2Mb Chip, HD FDD
> SCSI HDD's (never mind their size), Kickstart 3.1 (40.68), OS 3.5,
> Linux 2.0 (RedHat 5.1), C= A2065 and an Opalvision card
> - ("Designed in Australia", and keeping the Zorro bus populated).
> --
Re: How to cleanup when a class is destroyed ?
#441
Author: Ross Vumbaca
Date: Sat, 14 Oct 2000 00:00
29 lines
1461 bytes
Hi,

DavidL wrote:
 
> But what if I have a class something like:

<Snip>

People keep confusing your request with garbage collection, which Java
does. There is a "finalize" method for Java objects, which is run when
an object is trashed. Can't help much else though ;). The other post
with the javadocs link will help you.

Regards,

Ross.. 

-- 
*TO E-MAIL ME: Reverse the order of the domain name in my e-mail
address.*

Ross Vumbaca, a 'poor' Uni student at USyd.edu.au
http://www.fl.net.au/~rossv

Running on an Amiga 3000 (030/25), ECS, 8Mb Fast, 2Mb Chip, HD FDD
SCSI HDD's (never mind their size), Kickstart 3.1 (40.68), OS 3.5,
Linux 2.0 (RedHat 5.1), C= A2065 and an Opalvision card
- ("Designed in Australia", and keeping the Zorro bus populated).
--
Re: How to cleanup when a class is destroyed ?
#444
Author: Benjamin Johnston
Date: Sat, 14 Oct 2000 00:00
143 lines
5921 bytes
> I probably need to be more precise with my questions, so they can't be
> confused.
>
> I am aware of the finalize method, but, unfortunately, haven't seen it
work.

/snip/

> then when that app runs I would expect the "finalize called" message to be
> displayed, but it doesn't happen.
>
> Maybe my JVM is broken ?

Really, finalization isn't something you should be worrying about, its a C++
thing. In practice, you'll very rarely need to use finalize.

Anyway, to explain;

Firstly, say I've got a class;

public class Test {
     public void finalize() {
          System.out.println("finalize called");
     }

     public static void main(String[] args) {
          new Test();
     }
}

(This is functionally eqivalent to the classes that you posted, only it
takes up less screen space).

Ok, what happens...

1. Java starts up, calls main.
2. main creates the new instance of Test, and then the Main method exits.
3. Java automatically shuts down when there are no live threads, so when the
only thread (Main) exits, the VM decides to shut down too.

The VM shuts down. The VM doesn't finalize by default on shutdown. (There is
a brief explanation in the JavaDocs of why).


So, how do we see the finalize method work?... two ways...

Firstly, tell the VM to finalize every class before the VM shuts down;

public class Test {
     public void finalize() {
          System.out.println("finalize called");
     }

     public static void main(String[] args) {
          System.runFinalizersOnExit(true);
          new Test();
     }
}

After invoking System.runFinalizersOnExit(true); the VM will finalize every
object before shutting down. If the finalize methods do weird things, like
start creating new Threads or invoking other objects, you'll probably run
into problems. Anyway, the above code snippet prints "finalize called", as
desired.

runFinalizesOnExit is deprecated... you shouldn't really be doing it.


The other way we can see finalize in action is by forcing the Garbage
collector into action....

public class Test {

     private int[] memoryWaste = new int[1000];

     public void finalize() {
          System.out.println("finalize called");
     }

     public static void main(String[] args) {
          while (true) {
               new Test();
               System.gc();
          }
     }
}


Ok, this might pause for a while, and then might start spitting out
"finalize called".
(It does on my VM, it should on most VMs, but a VM isn't required to do
this)

This program continuously intantiates fairly large objects, and discards the
references (so its immediately available for garbage collection).

The call to System.gc() is ONLY A RECOMMENDATION to the VM. It is perfectly
ok for the VM to ignore such a request (in fact on my VM, it does ignore the
requests for a while). System.gc() is the programmer's way of saying "here's
a nice time to do some garbage collection, if you feel like it". It would be
perfectly legal for a VM to never garbage collect, and just keep wasting
more and more memory, even if you called System.gc() over and over again.


Finalize is something you really don't need to use. You cannot predict
exactly when its going to be called (if at all), and for this reason, its
only used in pretty specialized cases.


Because deletion isn't explicit in Java, finalization is much less
significant than it is in C++. In Java, you'll typically find that you'll
have a close() or discard() method to tell an object to 'clean up' -- which
you'd invoke when the operation is completed or the user clicks 'close'. If
you're new to Java, this might seem like a limitation, but I think you'll
find that once you're used to Java's style of doing things it doesn't get in
the way.

In practice you'll find that, say with sockets, it will be clear when
something need to be closed (you may put a close statement in the finally
clause of a try-catch). This is because such objects last either for a
particular command (you'd close the objects when the command is completed),
or they will last for the entire application's execution (so you'd close
them on shutdown).

File and Socket I/O usually has a clear place to put open/close. GUI cleanup
is automatic on VM shutdown, and discard methods are invoked when a frame is
hidden (and will not be shown again). Almost everything else is done for you
by the garbage collector (such as deallocating arrays and memory used by an
object).

The other thing you mentioned, physical ports aren't used often... but the
comm framework (a standard extension) has close methods, which you'd
probably find somewhere suitable to call them from.

While I'm reluctant to say this, here I go... in Java, when you create your
own close method it is like creating a method for explicitly
freeing/deallocating the object (except you leave the actual memory for the
garbage collector to clean up).

I hope that explains things.

-Benjamin Johnston
s355171@student.uq.edu.au
Re: How to cleanup when a class is destroyed ?
#445
Author: DavidL
Date: Sat, 14 Oct 2000 00:00
185 lines
7187 bytes
Thanks Benjamin for a comprehensive reply.

I guess I am used to an approach where I create an object, and then don't
have to worry about cleaning up because the object does all that itself.

As you said, a cleanup is usually required as a result of an error, or the
completion of some section of the application, and so it is possible to
explicitly call a close or cleanup method where required.

However, this requires a more structured design approach than I usually
adopt. So I guess I need to stop looking for an easy way to cleanup, and
instead go back and look at the problem I am trying to solve, and devise a
more structures solution.

Thanks
    DavidL

"Benjamin Johnston" <s355171@student.uq.edu.au> wrote in message
news:8s9jav$va1$1@bunyip.cc.uq.edu.au...
> > I probably need to be more precise with my questions, so they can't be
> > confused.
> >
> > I am aware of the finalize method, but, unfortunately, haven't seen it
> work.
>
> /snip/
>
> > then when that app runs I would expect the "finalize called" message to
be
> > displayed, but it doesn't happen.
> >
> > Maybe my JVM is broken ?
>
> Really, finalization isn't something you should be worrying about, its a
C++
> thing. In practice, you'll very rarely need to use finalize.
>
> Anyway, to explain;
>
> Firstly, say I've got a class;
>
> public class Test {
>      public void finalize() {
>           System.out.println("finalize called");
>      }
>
>      public static void main(String[] args) {
>           new Test();
>      }
> }
>
> (This is functionally eqivalent to the classes that you posted, only it
> takes up less screen space).
>
> Ok, what happens...
>
> 1. Java starts up, calls main.
> 2. main creates the new instance of Test, and then the Main method exits.
> 3. Java automatically shuts down when there are no live threads, so when
the
> only thread (Main) exits, the VM decides to shut down too.
>
> The VM shuts down. The VM doesn't finalize by default on shutdown. (There
is
> a brief explanation in the JavaDocs of why).
>
>
> So, how do we see the finalize method work?... two ways...
>
> Firstly, tell the VM to finalize every class before the VM shuts down;
>
> public class Test {
>      public void finalize() {
>           System.out.println("finalize called");
>      }
>
>      public static void main(String[] args) {
>           System.runFinalizersOnExit(true);
>           new Test();
>      }
> }
>
> After invoking System.runFinalizersOnExit(true); the VM will finalize
every
> object before shutting down. If the finalize methods do weird things, like
> start creating new Threads or invoking other objects, you'll probably run
> into problems. Anyway, the above code snippet prints "finalize called", as
> desired.
>
> runFinalizesOnExit is deprecated... you shouldn't really be doing it.
>
>
> The other way we can see finalize in action is by forcing the Garbage
> collector into action....
>
> public class Test {
>
>      private int[] memoryWaste = new int[1000];
>
>      public void finalize() {
>           System.out.println("finalize called");
>      }
>
>      public static void main(String[] args) {
>           while (true) {
>                new Test();
>                System.gc();
>           }
>      }
> }
>
>
> Ok, this might pause for a while, and then might start spitting out
> "finalize called".
> (It does on my VM, it should on most VMs, but a VM isn't required to do
> this)
>
> This program continuously intantiates fairly large objects, and discards
the
> references (so its immediately available for garbage collection).
>
> The call to System.gc() is ONLY A RECOMMENDATION to the VM. It is
perfectly
> ok for the VM to ignore such a request (in fact on my VM, it does ignore
the
> requests for a while). System.gc() is the programmer's way of saying
"here's
> a nice time to do some garbage collection, if you feel like it". It would
be
> perfectly legal for a VM to never garbage collect, and just keep wasting
> more and more memory, even if you called System.gc() over and over again.
>
>
> Finalize is something you really don't need to use. You cannot predict
> exactly when its going to be called (if at all), and for this reason, its
> only used in pretty specialized cases.
>
>
> Because deletion isn't explicit in Java, finalization is much less
> significant than it is in C++. In Java, you'll typically find that you'll
> have a close() or discard() method to tell an object to 'clean up' --
which
> you'd invoke when the operation is completed or the user clicks 'close'.
If
> you're new to Java, this might seem like a limitation, but I think you'll
> find that once you're used to Java's style of doing things it doesn't get
in
> the way.
>
> In practice you'll find that, say with sockets, it will be clear when
> something need to be closed (you may put a close statement in the finally
> clause of a try-catch). This is because such objects last either for a
> particular command (you'd close the objects when the command is
completed),
> or they will last for the entire application's execution (so you'd close
> them on shutdown).
>
> File and Socket I/O usually has a clear place to put open/close. GUI
cleanup
> is automatic on VM shutdown, and discard methods are invoked when a frame
is
> hidden (and will not be shown again). Almost everything else is done for
you
> by the garbage collector (such as deallocating arrays and memory used by
an
> object).
>
> The other thing you mentioned, physical ports aren't used often... but the
> comm framework (a standard extension) has close methods, which you'd
> probably find somewhere suitable to call them from.
>
> While I'm reluctant to say this, here I go... in Java, when you create
your
> own close method it is like creating a method for explicitly
> freeing/deallocating the object (except you leave the actual memory for
the
> garbage collector to clean up).
>
> I hope that explains things.
>
> -Benjamin Johnston
> s355171@student.uq.edu.au
>
>
>
Re: How to cleanup when a class is destroyed ?
#446
Author: Paul Murray
Date: Sat, 14 Oct 2000 00:00
24 lines
1556 bytes
"DavidL" <email.address@in.message> wrote in message
news:39e57bc3$1@server.local...
> Hi all,
>
> I have come to java from C++, where when you want to cleanup when a class
is
> destroyed you would write a destructor.
>
> I am having trouble getting the same functionailty from java.
>
> From what I have read, I understood that this was the function of the
> "finalize" method.
> However, I don't seem to be able to get it to work.
>

Java does not guarrintee that finalize gets called, although there is a flag
you can set that will actually do this. rather than handling clean-up as a
side effect of memory management, you will need to clean up your classes
expicitly.

--------------------------------------------------------------
Repent! Quit your job! Slack off!
http://www.users.bigpond.com/pmurray
ICQ: 26066755
Re: How to cleanup when a class is destroyed ?
#447
Author: Paul Murray
Date: Sat, 14 Oct 2000 00:00
13 lines
1256 bytes
"DavidL" <email.address@in.message> wrote in message
news:39e62821$1@server.local...

> How do I ensure that the close() method is called ?
> It is unreasonable to expect that the application will always call the
> close() method, especially if there is an error.

You catch errors and handle them properly.

--------------------------------------------------------------
Repent! Quit your job! Slack off!
http://www.users.bigpond.com/pmurray
ICQ: 26066755
Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads