Javadoc
An
AutoReferenceCounted is an object which can be registered with an
AutoReferenceCountedReaper instance to have resources closed prior to being garbage
collected.
AutoReferenceCounted is similar to reference counting, except that the
reference counting is performed by the JVM garbage collector. Users of
AutoReferenceCounted objects need only to register the object with an
AutoReferenceCountedReaper upon creation; no explicit life-cycle management needs to be
done. The object's resources will automatically be released when the
AutoReferenceCountedis claimed by the garbage collector.
AutoReferenceCounted and
AutoReferenceCountedReaper use the
java.lang.ref.PhantomReference mechanism of the JVM to ensure that no threads have a
reference to the
AutoReferenceCounted before closing the resources of the
AutoReferenceCounted.
To fulfill the
AutoReferenceCounted interface, classes must define the
#getCloseableResources() method, which must return the
Closeable resources held
by the instance.
*Special Note* because cleanup relies on the
AutoReferenceCounted no longer being
reachable, users of
AutoReferenceCounted instances must take special care to hold a
strong reference to instances while in use, and to let go of the reference after the
AutoReferenceCounted is no longer needed. Non-static inner-classes hold a reference to their
outer class, so the same care should be taken with non-static inner-class instances of an
AutoReferenceCounted. In particular, do *not* return a non-static inner class from
#getCloseableResources, as this will cause the
AutoReferenceCounted to never be
collected due to a reachable cyclical reference.