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

Jaroslav Tulach jaroslav.tulach at
Wed Aug 6 10:17:38 UTC 2014

time to show the code. I've added an alternative patch to JDK-8051843:
I suggest to start reading it from bottom - e.g. the test, the documentation 
and then the implementation. 

Now there is time for some discussion: First of all I should mention that the 
patch is sufficient to solve all the problems NetBeans and people reusing 
NetBeans libraries in dynamic classloader systems (e.g. containers) have. This 
is a pro.

Next thing to check is whether the change can cause some harm. Here are the 
areas of concern we have identified so far:

> > > # 1 - Because of automatic JDK management thread?

The patch introduces no new thread. It reuses already existing one. No 
allocation of new system resources. Status quo is kept.

On the other hand, this is a pro over own ReferenceQueue.remove calls. One 
saves a thread per instance of such queue.

> > > # 2 - Or because once finalize() is called, one still has reference to
> > > the
> > > "gone" object and can re-activate it?

This problem does not exist with activeQueue(). When the run() method on a 
Reference is called, this.get() already returns null. I believe this addresses 
also David M. LLoyd's concern:

> Yup.  Did you know that an object can be finalized while there are still
> instance methods of that object executing?  We've actually seen it

Sure, but that cannot happen with activeQueue() as the referent is really gone 
before appropriate is executed.

Certainly a pro over Object.finalize. Status quo with respect to ReferenceQueue 
as that behaves the same.

> > > #3 - Or because the finalizer thread is shared between completely
> > > unrelated
> > > objects and misbehavior of one can cause problems for others?

No regression in this aspect either. finalizer thread already has this problem, 
and we are not making it worse. Status quo is kept. Well written application 
actually benefit from this behavior, as they save system threads (compared to 
own ReferenceQueue.remove implementations).

> If you still think that finalize is a good idea, given that it's
> basically defective *and* there is almost always a better solution, 

I believe activeQueue() in core libraries is good idea. Because it fills the 
gap between (dangerous, unusable) Object.finalize and (ineffective) attempts to 
code the same logic in libraries (via own Thread+ReferenceQueue.remove)

I see at least one pro and no cons. Are there other points of view?

More information about the core-libs-dev mailing list