Java Reference
In-Depth Information
Accessing and Clearing a Referent's Reference
You will use objects of a trivial class to demonstrate the use of reference classes. This class, called BigObject , is shown in
Listing 11-4. It has a big array of long as an instance variable, so it uses a big chunk of memory. The id instance variable
is used to track the objects of this class. The finalize() method prints a message on the console using the object's id .
Listing 11-4. A BigObject Class, Which Uses Big Memory
// BigObject.java
package com.jdojo.gc;
public class BigObject {
// Declare a 32KB array. This choice is arbitrary. We just wanted to use a large
// amount of memory when an object of this class is created.
private long [] anArray = new long[4096];
// Have an id to track the object
private long id;
public BigObject(long id) {
this.id = id;
}
// Define finalize() to track the object's finalization
public void finalize(){
System.out.println("finalize() called for id:" + id);
}
public String toString() {
return "BigObject: id = " + id;
}
}
The object that you pass to the constructors of the WeakReference , SoftReference , and PhantomReference
classes is called a referent . In other words, the object referred to by the object of these three reference classes is called
a referent. To get the reference of the referent of a reference object, you need to call the get() method.
// Create a big object with id as 101
BigObject bigObj = new BigObject(101);
/* At this point, the big object with id 101 is strongly reachable */
// Create a soft reference object using bigObj as referent
SoftReference<BigObject> sr = new SoftReference<BigObject>(bigObj);
/* At this point, the big object with id 101 is still strongly reachable,
because bigObj is a strong reference referring to it. It also has a soft reference
referring to it.
*/
// Set bigObj to null to make the object softly reachable
bigObj = null;
 
Search WWH ::




Custom Search