Why is finalize wrong? was: Benefits of activeReferenceQueue
jaroslav.tulach at oracle.com
Tue Jul 29 09:24:13 UTC 2014
the following suggestions are hard to argue with as they touch philosophical
aspects of software engineering. In spite of that I will attempt to analyze
Dne Út 29. července 2014 18:16:24, David Holmes napsal(a):
> I think the fundamental flaw of activeReferenceQueue is in trying to
> hide the thread management from the user.
I guess this builds on top of bad experience with Object.finalize() method. No
doubt existence of the method is failure, but why?
# 1 - Because of automatic JDK management thread?
# 2 - Or because once finalize() is called, one still has reference to the
"gone" object and can re-activate it?
#3 - Or because the finalizer thread is shared between completely unrelated
objects and misbehavior of one can cause problems for others?
My personal top three starts with #2. That is logically invalid. #3 can be a
problem, but so can be any other misbehaving thread in an application. #1 is
completely OK, from my perspective (if the thread can GC when necessary).
I'd like to point out that activeReferenceQueue does not have #2 problem at
all. So in my eyes it behaves fine (once we allow its thread to GC properly).
> By automating the threading
> there is no way to control the lifecycle of the thread and hence we have
> the problem at hand. When the application code manages the thread
> itself, then it can also manage its lifecycle and avoid the problem.
Alas, the primary (and only generally available) way to find out that something
is not used in Java SE is wait when it gets garbage collected, right?
Application frameworks on top of Java have notion of a lifecycle, but it is
different for Servlets, for NetBeans Platform, and any other framework. When
writing general purpose library in Java, GC is the only tool in hand.
> This might be a case where some kind of user-level "reference counting"
> would be a better solution. But of course that would require changes to
> all existing users of the class.
We tried some reference counting, but it is not reliable. Of course, all
problems in software engineering can be solved by yet another level of
indirection - I can create my own wrapper for WeakReference, ReferenceQueue
and etc. and then I have everything under my control. But why not slightly
improve the existing library and make it more flexible?
More information about the core-libs-dev