SoftReference
, WeakReference
, PhantomReference
may be used to customize the process of garbage collection. All of them extend Reference<T>
therefore it is possible to mix them in single collection. Hard references (most common ones) do no extend Reference<T>
therefore it is not possible to mix hard and other types of references in one collection. Am I right and we should put CustomReference<T> extends Reference<T>
to the collection in order to achieve the desired result of mixing all types of object links in single collection (Collection<Reference<T>>
)?
UPDATE: So when writing SSCCE I've found that it is not possible to extend Reference<T>
in a usual way (constructor is package-local).
So the question now updates to the following: can I with single collection class create cache which always holds some objects (say 10) and the others are reclaimed by GC when memory not allows? Is there any other means to do this except providing custom wrappers for hard and soft references and storing them in the collection?
Unfortunately Reference<T>
most not (and can not) be subclassed directly, according to its JavaDoc:
Because reference objects are implemented in close cooperation with the garbage collector, this class may not be subclassed directly.
As such you won't be able to easily (i.e. without ugly instanceof
+ casting) handle both soft/weak/phantom references and normal references in the same Collection
.
You could write a wrapper that either uses two separate Collection
objects to handle normal and soft/weak/phantom references or that puts them all into the same Collection<Object>
and uses the appropriate instanceof
checks with casts to differentiate the objects.