An implementation of
SingletonFactory, which provides some support for handling
cases where the output class instance holds a reference to the input class instance.
A
WeakHashMap is used as the underlying store. This ensures that if the input class
instance become otherwise unused (weakly reachable), the input class instance key used
within the factory will not prevent the input class from being garbage-collected,
thereby preventing a memory leak.
This class differs from
AbstractSimpleSingletonFactory in that output value instances
stored and returned by the factory are also wrapped internally in a
WeakReference.
This class should be used in cases where the output class holds a reference to the input
class key, so as not to prevent the described weak reference-based garbage collection
of the input class key, and thereby avoiding a memory leak.
Because the output instance is held in a WeakReference, it is subject to aggressive
garbage collection if it is otherwise weakly reachable (i.e. no strong or soft references
to it are held outside of this factory), ostensibly defeating the purpose of this factory.
Therefore if the lifecycle of external strong or soft references to any obtained output
instances obtained from the factory is shorter than the desired lifecyle of the output instance
(i.e. callers do not hold a strong or soft reference to an output instance for at least as
long as to the input instance), then an option requireExplicitRelease
is provided
that causes the factory to internally maintain a strong reference to each output instance.
This inhibits the garbage collection of the output instance. If this option is enabled,
then callers must explicity indicate when the output instance may be garbage collected by
calling
#release(Object). Failure to release an output instance when necessary
will result in a memory leak of the output instance as well as the input instance (if
the output instance holds a strong or soft reference to the input instance).
The default value of requireExplicitRelease
is false
. This is appropriate
for cases where calling code holds long-lived strong or soft references to the output instance,
typically as long or longer than references to the corresponding input instance, or where explict release
is undesirable or impractical.
Subclasses of this class might also implement automatic release of output instances,
instead of or in addition to, the explicit release mechanism supported by this class.
This might be based for example on mechanisms such as object aging or a fixed size FIFO queue.