• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

garbage collection and finalize method- inconsistent result

 
Anu Bhagat
Ranch Hand
Posts: 64
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I developed a small code to clarify my understanding of finalize method. I undersatnd it runs only once in an objects life.

my program print 112 or 121.
it looks like finalize is running on t1 again...which I think is not possible...so what is happening? please help me understand.



Thanks.

Anu
 
Paul Clapham
Sheriff
Pie
Posts: 20161
23
MySQL Database
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anu Bhagat wrote:I developed a small code to clarify my understanding of finalize method. I undersatnd it runs only once in an objects life.


However the API documentation says:
The finalize method is never invoked more than once by a Java virtual machine for any given object.


That must mean something different than "it runs only once in an object's life", then. Can you suggest what the difference might be?
 
Ruben Soto
Ranch Hand
Posts: 1032
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason why finalize() is running twice for t1 is because you are calling it explicitly from your code. The GC will only call finalize() once for each instance, but you can call it as many times as you want from your code. When you call it from your code that doesn't count as long as the GC goes. The GC will always call finalize() before reclaiming the memory for the object, and when it does, it will call finalize() exactly once.
 
Anu Bhagat
Ranch Hand
Posts: 64
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.
Anu
 
Anand A. Parikh
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Don't all methods of class Object have access modifier public?
In the above example how does
protected void finalize() { ... }

compile? and override the Object method?

Thanks,
Anand
 
Henry Wong
author
Marshal
Pie
Posts: 20820
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A Parikh wrote:
Don't all methods of class Object have access modifier public?
In the above example how does
protected void finalize() { ... }

compile? and override the Object method?

Thanks,
Anand


Please start new topics for new questions. First, it is kinda impolite to hijack another topic. Second, when you start a new topic, hopefully, you will create a new (relevant) subject which can be used by users to search with (in the future).

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic