|
A Case for Using Weak References
by Merwyn Welcome We want to hear from you! Please send us your FEEDBACK. The following Technical Article may contain actual software programs in source code form. This source code is made available for developers to use as needed, pursuant to the terms and conditions of this license.
OverviewWeak references allow a program to maintain a reference to an object that does not prevent the object from being considered for reclamation by the garbage collector. They also allow a program to be notified when the collector has determined that an object has become eligible for reclamation. Weak references are useful for: building simple caches as well as caches that are flushed only when memory is low; implementing mappings that do not prevent their keys (or values) from being reclaimed, and scheduling post-mortem cleanup actions in a more flexible way than is possible with the Java[tm] programming language's finalization mechanism. For more information on weak references and other types of references, see The Java Class Libraries Second Edition, Volume 1 (Supplement for Java[tm] 2 Platform Standard Edition, v1.3), page 696 to 702: java.lang.ref Reference1. Weak references are a preferred alternative to finalize methods. Because finalize() methods are only run when an object becomes eligible for garbage collection, this usually means that objects waiting to be finalized are held longer than objects that are referenced through weak references. The following example adds a key to a WeakHashMap. It then creates a thread that repeatedly checks whether the key is still in the map. The thread uses a copy of the key rather than the original key to check for the presence of the key in the map. (The thread cannot hold the original key; otherwise, the key would never be removed from the map.) If this example used a HashMap object instead, objects would have to wait longer before they were considered for reclamation by the garbage collector. The main() method then waits for you to type RETURN. Doing this sets the key fields to 'null', thereby releasing all references to the key. At some point in the future, the garbage collector will reclaim the key and cause the entry to be removed from the map. The thread then exits. The call to System.gc() is not necessary; the garbage collector will eventually reclaim the key. Calling it is simply a suggestion that garbage collection take place. The system may ignore the call, depending on the implementation of the Java[tm] virtual machine.
Exampleimport java.util.*; class WeakHashMapExample implements Runnable { static WeakHashMap map = new WeakHashMap();
public static void main(String[] args) { map.put(key, null);
try {
key = null;
public void run() { Integer keyCopy = new Integer(123); while (map.containsKey(keyCopy))
{
Resources 1http://java.sun.com/docs/books/tutorial/post1.0/preview/weak.html
| |||||||||||||||||||||||||||||||||||||||