Do SoftReference
and WeakReference
really only help when created as instance variables? Is there any benefit to using them in method scope?
The other big part is ReferenceQueue
. Besides being able to track which references are determined garbage, can Reference.enqueue()
be used to forcibly register an object for garbage collection?
For example, would it be worth to create a method that takes some heavy memory resources (held by strong references) in an object and creating References to enqueue them?
Object bigObject;
public void dispose() {
ReferenceQueue<Object> queue = new ReferenceQueue<Object>();
WeakReference<Object> ref = new WeakReference<Object>(bigObject, queue);
bigObject = null;
ref.enqueue();
}
(Imagine that Object in this case represents an object type that uses a lot of memory... like BufferedImage
or something)
Does this have any realistic effect? Or is this just a waste of code?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…