Java Reference
In-Depth Information
The clear() method clears the link between the reference (weak, soft, or phantom) object and its referent. The
following piece of code illustrates its use:
// Create a soft reference object. Use a BigObject with id 976 as its referent.
SoftReference<BigObject> sr1 = new SoftReference<BigObject> (new BigObject(976));
/* At this point, the BigObject with id 976 is softly reachable, because it is reachable only
through a soft reference sr.
*/
// Clear the referent
sr1.clear();
/* At this point, the big object with id 976 is unreachable (to be exact, it is finalizer-
reachable), because we cleared the only one reference soft reference) we had to the object.
*/
The memory state with all references, after each statement in the above snippet of code is executed, is depicted in
Figure 11-7 . After the referent's reference is cleared using the clear() method, the get() method returns null . Note
that the get() method of a PhantomReference object always returns null .
sr1
SoftReference
Object
id:976
X
SoftReference<BigObject> sr1 = new SoftReference<BigObject>(new BigObject(976));
sr1
SoftReference
Object
id:976
X
SoftReference<BigObject> sr1 = new SoftReference<BigObject>(new BigObject(976));
sr1.clear( )
Figure 11-7. Clearing referent
Using the SoftReference Class
A softly reachable object is used to maintain memory-sensitive caches. That is, if you want to maintain a cache
of objects as long as the program is not running low in memory, you can use softly reachable objects. When the
program runs low in memory, the garbage collector clears the soft references to an object, making the object eligible
for reclamation. At that point, your program will lose some or all objects from the cache. Java does not guarantee
that soft references will not be cleared if the program is not running low in memory. However, it guarantees that all
soft references will be cleared before the JVM throws an OutOfMemoryError . There is also no guarantee of the order
in which soft references will be cleared. However, JVM implementations are encouraged to clear the least-recently
created/used soft reference first.
 
Search WWH ::




Custom Search