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: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 sameCollection.You could write a wrapper that either uses two separate
Collectionobjects to handle normal and soft/weak/phantom references or that puts them all into the sameCollection<Object>and uses the appropriateinstanceofchecks with casts to differentiate the objects.