finalization vs References

Bryce McKinlay bryce@albatross.co.nz
Thu May 11 18:41:00 GMT 2000


Per Bothner wrote:
> I gather that finalization is rather expensive, at least as
> implemented in libgcj. Any feelings on whether it is more
> or less expensive that using Java2 References?

I've been looking at implementing these. Classpath has a nice
implementation of the java.lang.ref classes, and I think that support for
WeakReference and PhantomReference at least should be fairly simple to
implement in the collector. SoftReference could be a bit trickier.
Finalization isn't particularly expensive in libgcj, if anything its
cheaper than using Reference objects because of the memory overhead of
the reference objects themselves. Functionally, they are quite different,
so the decision of which to use really depends on the situation. If you
have "control" over the object's class (ie you're writing it), then its
usually simpler and more appropriate to write a finalizer. If you want to
be notified that some "foreign" object is ready to be collected, or want
to maintain access to an object only while it hasn't been collected, then
you need to use a weak or a phantom reference.
One difference is that you have no control over when a finalizer might
get run. Currently we run finalizers from inside the allocator, but that
is rather broken and will soom be changed to an asynchronous finalization
thread. WeakReference objects, on the other hand, are enqueued
synchronously from within the allocator as soon as the object is found to
be unreachable, and the ReferenceQueue mechanism gives you more
flexibility over when and where your cleanup actions get run.
regards
 [ bryce ]


More information about the Java mailing list

AltStyle によって変換されたページ (->オリジナル) /