ReferenceQueue<Integer> queueObj = new ReferenceQueue<Integer>();
WeakReference<Integer> referenceObj = new WeakReference<Integer>(new Integer(1), queueObj);
I understand above like this,
- First, create WeakReference referenceObj object for new Integer(1) object.
- Second, system move referenceObj object into queueObj object. Now queueObj has referenceObj element.
- Third, system GC the new Integer(1) object, and clear queueObj object. Now queueObj is empty.
Correctly?
EDIT:
- First, create WeakReference referenceObj object for new Integer(1) object.
- Second, system move referenceObj object into queueObj object. Now queueObj has referenceObj element, new Integer(1) object has be collected by system.
- Third, some program detect queueObj whether is empty or not. if not, you know some referent was collected, and you can iterate queueObj to handle referenceObj.
First and second, correct. Third, incorrect. It is up to you to process the ReferenceQueue, remove entries, act on whatever the entry means to your application, etc. For example, WeakHashMap processes the ReferenceQueue in the background to know when to remove items from the map.