9. 31. 2. Understanding Weak References |
|
- Reference class is defined in the java.lang.ref package.
- Instead of providing variables that directly reference your memory, you create a reference object that indirectly holds a reference to the object.
- The reference objects are then maintained in a reference queue (ReferenceQueue), which monitors the references for reachability by the garbage collector.
|
There are four types of references to objects. |
- Direct references like you normally use, as in Integer i = new Integer(13), are called strong references and have no special class. The remaining three are soft references (SoftReference), weak references (WeakReference), and phantom references (PhantomReference).
- Soft references are like a cache. When memory is low, the garbage collector can arbitrarily free up soft references if there are no strong references to the object. If you are using soft references, the garbage collector is required to free them all before throwing an OutOfMemoryException.
- Weak references are weaker than soft references. If the only references to an object are weak references, the garbage collector can reclaim the object's memory at any time-it doesn't have to wait until the system runs out of memory. Usually, it will be freed the next time the garbage collector runs.
- Phantom references are special. They allow you to be notified before the garbage collector performs finalization and frees the object. Think of it as a mechanism to perform cleanup.
|
(Referend from Ivor Horton's Beginning Java 2, JDK 5 Edition by Ivor Horton Wrox Press 2005) |