• Post Reply Bookmark Topic Watch Topic
  • New Topic

finalize() and garbage collection  RSS feed

 
john sayeau
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand that if you hava finalize() in your class it is run when an object is gc'd. Is it run only on a forced gc?
I ask because in the program below I believe I have 3 objects to be cleaned up but it looks as if finalize only runs 2 times. the code is from the "thinking in Java" book.

 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all you can't forge the GC. You can request it. The aBook is still in scope and because of that it's not GC'ed.
 
john sayeau
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oops.
I guess that first object still has a reference and won't be gc'd.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you should never attempt to call finalize() (unless under the catch-all excuse of "I just wanted to see what happens if . . . "); if you call it once when it isn't necessary, it might not be called when necessary by the JVM.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!