When using weak or soft reference with a ReferenceQueue when is the object really removed from memory?

480 Views Asked by At

When using weak or soft reference with a ReferenceQueue when is the object really removed from memory? Do I have to call referancequeue.remove or referancequeue.poll() methods?

Example:

ReferenceQueue q = new ReferenceQueue();
WeakReference wr = new WeakReference(object, referenceQueue);


if (pr.isenqueued()) {

   // do something

}

or do I have to following?

WeakReference weakref=null;

if ((weakref=q.removed())!=null) {

   // do something

}
2

There are 2 best solutions below

2
On

After you remove them from the ReferenceQueue, the object can be finalised and after they have been finalised they can be removed on the next GC.

0
On

In your example WeakReference will be cleaned by garbage collector when it's unreacheble. On the other hand if you use SoftReferences, softly reachable objects are kept as long as ther is enough memory. So if you want it to persist you should use SoftReference. I guess having the control i.e. 2nd way would give you a peace of mind. If you want to make the cleanup operations yourself instead of GC, to ensure the progress you can use PhantomReference instead. They aren't automatically cleared by the garbage collector before they are enqueued.