Reputation: 877
How does the ReferenceQueue works? and How to use it on Projects?
Documents said: When a WeakReference or SoftReference has been cleaned, they will be enqueue the ReferenceQueue. What does that do this?
Upvotes: 3
Views: 1528
Reputation: 4462
To understand ReferenceQueue first you need to understand the different between strong and weak references. Here's an article that can help you with that: https://community.oracle.com/blogs/enicholas/2006/05/04/understanding-weak-references
What is a ReferenceQueue?
Non-strong references start returning null once the heap object they weakly refer to don't have any strong references to them. So the problem with non-strong references is that you never know when they will start returning null. ReferenceQueue is a provision provided by Java to help us know when the weakreference is eligible for GC, if and when we really want to know that. So how this should be done? If you have provided a ReferenceQueue while creating the weakreference then when that weakreference is eligible for GC, it is en-queued into that ReferenceQueue and then you can keep polling that ReferenceQueue when you wanna check if any weakreference has been enqueued in the ReferenceQueue.
Here is a good article with code for this: http://learningviacode.blogspot.com/2014/02/reference-queues.html
Upvotes: 3