Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes Can anybody give me an example fo finalize()? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Can anybody give me an example fo finalize()?" Watch "Can anybody give me an example fo finalize()?" New topic
Author

Can anybody give me an example fo finalize()?

Wilson Yang
Greenhorn

Joined: Apr 24, 2008
Posts: 7
Can anyone give me an example of finalize()? Including how to use and override it.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
You only really want to use finalize() to clear up non-Java resources. You will only really need it when closing "native" code for reading files etc.

If you search round the Sun Java website, somewhere there is a sample chapter from Joshua Bloch's Effective Java, 1st edition. You should find a discussion of finalize() in that. I can't remember where you will find it, I am afraid.
Wilson Yang
Greenhorn

Joined: Apr 24, 2008
Posts: 7
Thanks a lot.
Mark Vedder
Ranch Hand

Joined: Dec 17, 2003
Posts: 624

Originally posted by Campbell Ritchie:
I can't remember where you will find it, I am afraid.


Chapter 2, item #7
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19719
    
  20

Important note:

You can't assume that finalize() will be called. All the Java Language Specification guarantees is that for any object, finalize() will be called at most once.

Because of this, it's always wise to clean up your resources yourself, yet still include the cleaning up in finalize() just in case someone forgot to call the clean up method. In pseudo code:

It's always a good idea to call super.finalize no matter what happens. If your own finalization can throw an exception, put super.finalize() in a finally block:

[ July 27, 2008: Message edited by: Rob Prime ]

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can anybody give me an example fo finalize()?