• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can anybody give me an example fo finalize()?

 
Wilson Yang
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone give me an example of finalize()? Including how to use and override it.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49793
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot.
 
Mark Vedder
Ranch Hand
Posts: 624
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Campbell Ritchie:
I can't remember where you will find it, I am afraid.


Chapter 2, item #7
 
Rob Spoor
Sheriff
Pie
Posts: 20608
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic