user1764890
user1764890

Reputation: 19

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

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

}

Upvotes: 1

Views: 479

Answers (2)

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.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533740

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.

Upvotes: 0

Related Questions