A weak reference is similar to a soft reference, except that objects that are weakly reachable will be garbage collected before objects that are softly reachable. When the JVM needs memory, it will first reclaim all unused objects, if the reclaimed memory is still not sufficient, then all weakly referenced objects will will be garbage collected, and if it needs even more memory, then it will reclaim memory from softly referenced objects.
WeakReference wr = new WeakReference(new String(“abc”));
ReferenceQueue rq = new ReferenceQueue();
WeakReference wr = new WeakReference(new PhantomReference(new String(“abc”), queue));
String s = new String(“abc”);
ReferenceQueue queue = new ReferenceQueue();
WeakReference wr = new WeakReference(s);
PhantomReference pr = new PhantomReference(s, queue);
s = null;
All of the above are examples of weak references. In the above example we see two new concepts; phantom reference, and reference queue. More about them in the next section.
Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net
Comments