• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

finalize() will always be called

 
Barkat Mardhani
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In "Thinking in Java" chapter 4 question 11 and 12 are as follows:

11. Create a class with a finalize( ) method that prints a message. In main( ), create an object of your class. Explain the behavior of your program. Comment
12. Modify Exercise 11 so that your finalize( ) will always be called. Comment

I thought we can not be certain that finalize will be
called. It is up to JVM even after System.gc call
 
Barb Hart
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure if this is what the book meant... but you could call the finalize() method from a try/finally block. The finally should 'always' be executed, unless the thread is killed or system.exit happens first.
Barbara Hart
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please have a look at the following discussions on that topic:
http://www.coderanch.com/t/238828/java-programmer-SCJP/certification/GC
Also the API docs for the finalize() method state:

protected void finalize()
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
...
The finalize method is never invoked more than once by a Java virtual machine for any given object.
...

[ August 15, 2002: Message edited by: Valentin Crettaz ]
 
Paul Villangca
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Valentin,

I'm pretty sure that not all of us have the F: drive mapped the same as yours.
Anyway, using the finalize() method is generally not advisable, as it's execution is unpredictable.
Paul
[Link fixed by Val]
[ August 15, 2002: Message edited by: Valentin Crettaz ]
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry guys, I fixed the link
 
Barb Hart
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just came across this article in Java World on garbage collection and finalization. It explains system.gc() and system.runFinalization(). Although, as discussed in the other links and this article, even calling system.runFinalization() doesn't guarantee that it will run.
http://www.javaworld.com/javaworld/jw-12-2001/jw-1207-java101-p3.html
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic