Weak reference: Difference between revisions

Content deleted Content added
No edit summary
Line 33:
 
public class ReferenceTest {
public static void main(String[] args) throws InterruptedException {
WeakReference r = new WeakReference("I'm here");
StrongReference sr = new StrongReference("I'm here");
System.out.println("beforeBefore gc: r=" + r.get() + ", static=" + sr.get());
System.gc();
Thread.sleep(100);
 
// onlyOnly r.get() becomes null.
WeakReference r = new WeakReference("I'm here");
System.out.println("afterAfter gc: r=" + r.get() + ", static=" + sr.get());
StrongReference sr = new StrongReference("I'm here");
}
System.out.println("before gc: r=" + r.get() + ", static=" + sr.get());
System.gc();
Thread.sleep(100);
 
// only r.get() becomes null
System.out.println("after gc: r=" + r.get() + ", static=" + sr.get());
 
}
}
 
</source>
Another use of weak references is in writing a [[cache (computing)|cache]]. Using, for example, a weak [[hash map]], one can store in the cache the various referred objects via a weak reference. When the garbage collector runs &mdash; when for example the application's memory usage gets sufficiently high &mdash; those cached objects which are no longer directly referenced by other objects are removed from the cache.
Line 98 ⟶ 95:
 
===[[Vala (programming language)|Vala]]===
<source lang="vala">
class Node {
public weak Node prev; // a weak reference is used to avoid circular references between nodes of a doubly-linked list
Line 105 ⟶ 102:
</source>
 
===Python3Python===
<source lang=python3"pycon">
>>> import weakref
>>> import gc