Lightweight finalization for the JDK without any drawbacks was: Why is finalize wrong?

Andrew Haley aph at redhat.com
Fri Aug 8 12:47:33 UTC 2014


On 08/08/2014 11:55 AM, Jaroslav Tulach wrote:
> Dne Pá 8. srpna 2014 10:01:14, Andrew Haley napsal(a):
> 
>> On 08/08/14 09:01, Jaroslav Tulach wrote:
>> > Given the fact that WeakReference & co. has been introduced in JDK
>> > 1.2 and that version was released at the end of 1998, I bet it was
>> > just a communication problem, as Andrew must have been talking about
>> > something else than WeakReference + ReferenceQueue behavior.
>>
>> You don't have to believe me, read this:
>>
>> http://thevirtualmachinist.blogspot.co.uk/2011/07/subtle-issue-of-reachability.html
>  
> Interesting, but not really related.

Your question was "Why is finalize wrong?"  This is one reason that I
consider finalization (which includes finalizers, weak references, and
phantom references) to be wrong, so it is a direct answer to your
question.  That, and the fact that finalizable objects may end up in a
region which is never collected.

So: finalization can happen too early, too late, or never.  It is
difficult to use and error-prone, so much so that I suspect that most
finalizers out in the wild are broken.

> Maybe a topic for the memory management group to require a receiver
> of an instance method call to be considered GC root while the method
> is running.

I think that one has been considered and rejected.  It would add
pressure to register-straved machines (think x86).

> Btw. if anyone really gets into problems described in the article, this:

Yes, people really do get into those problems.

There are lots of things one can do to defer finalization, some of
them more lightweight than using a logger.  We've tried many of them.
My current favourite is AtomicIntegerFieldUpdater.lazySet(), which I
think cannot be optimized away, but a smart compiler may realize that
the object is not reachable from other threads and eliminate it.
Maybe.

> My assumption is that the Logger.log call is so polymorphic that it
> won't be possible for a VM to inline it and/or optimize away - even
> it is usually a no-op.

But would you bet the farm on that assumption?  HotSpot is very good
at inlining polymorphic calls.

Andrew.



More information about the core-libs-dev mailing list