Content deleted Content added
No edit summary |
|||
Line 33:
public class ReferenceTest {
▲ WeakReference r = new WeakReference("I'm here");
▲ 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 — when for example the application's memory usage gets sufficiently high — 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>
===
<source lang=
>>> import weakref
>>> import gc
|