Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #30488

Re: finalize() not called.

From Joshua Cranmer 🐧 <Pidgeot18@verizon.invalid>
Newsgroups comp.lang.java.programmer
Subject Re: finalize() not called.
Date 2014-12-04 14:24 -0600
Organization A noiseless patient Spider
Message-ID <m5qftc$uuu$1@dont-email.me> (permalink)
References <850b3ab9-57ea-490c-a165-943183169841@googlegroups.com>

Show all headers | View raw


On 12/4/2014 10:56 AM, somenathpal@gmail.com wrote:
> Now when System.gc() is called I expect finalize() to be called. But
> it does not get called. But when I uncomment the following
> System.out.println("Calling GC"); the finalize() gets called. I am
> not able to understand this behavior. I was expecting finalize()
> method yo be called. Could you please explain the behavior.

Garbage collectors are very complex beasts, so all I can do is speculate 
on the behavior.

A modern garbage collector is concurrent--it runs in a separate thread, 
all the time. The point of the garbage collector is that it frees you 
from worrying about when memory is freed--it is freed no earlier than it 
could be freed. But that's not a tight constraint as to when the memory 
will be freed (and tightly constraining that would destroy the 
performance)--it will eventually happen.

When you call System.gc(), that is semantically an advisory to the 
garbage collector that it should run. This effectively amounts to 
posting an event to the GC to start a collection. Since your program 
exits immediately afterwards, it's basically a race to see if the 
finalizer is executed first or the program exits first.

finalize() is meant, primarily, for cleaning up resources (e.g., file 
descriptors) if the instance wasn't closed before becoming dead code. 
It's only a reliable as a "just-in-case someone forgot to do this, don't 
leak," and not as a replacement for C++ destructors. If you need 
destructor-like functionality, you really should be using the 
try-resource blocks feature added in Java 7.

-- 
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth

Back to comp.lang.java.programmer | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

finalize() not called. somenathpal@gmail.com - 2014-12-04 08:56 -0800
  Re: finalize() not called. Robert Klemme <shortcutter@googlemail.com> - 2014-12-04 20:37 +0100
  Re: finalize() not called. v_borchert@despammed.com (Volker Borchert) - 2014-12-04 19:05 +0000
  Re: finalize() not called. Joshua Cranmer 🐧 <Pidgeot18@verizon.invalid> - 2014-12-04 14:24 -0600
  Re: finalize() not called. Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-12-06 16:07 -0500
    Re: finalize() not called. Lew <lewbloch@gmail.com> - 2015-01-04 16:13 -0800

csiph-web