在以下程序代码中,执行完第④行后,"hello"对象仅仅具有弱引用。接下来两次调用System.gc()方法,催促垃圾回收器工作,从而提高 "hello"对象被回收的可能性。假如"hello"对象被回收,那么WeakReference对象的引用被加入到ReferenceQueue中,接下来wf.get()方法返回null,并且rq.poll()方法返回WeakReference对象的引用。显示了执行完第⑧行后内存中引用与对象的关系。
String str = new String("hello"); //①
ReferenceQueue<String> rq = new ReferenceQueue<String>(); //②
WeakReference<String> wf = new WeakReference<String>(str, rq); //③
str=null; //④
//两次催促垃圾回收器工作,提高"hello"对象被回收的可能性
System.gc(); //⑤
System.gc(); //⑥
String str1=wf.get(); //⑦ 假如"hello"对象被回收,str1为null
Reference<? extends String> ref=rq.poll(); //⑧
在以下例程11-15的References类中,依次创建了10个软引用、10个弱引用和10个虚引用,它们各自引用一个Grocery对象。从程序运行时的打印结果可以看出,虚引用形同虚设,它所引用的对象随时可能被垃圾回收,具有弱引用的对象拥有稍微长的生命周期,当垃圾回收器执行回收操作时,有可能被垃圾回收,具有软引用的对象拥有较长的生命周期,但在Java虚拟机认为内存不足的情况下,也会被垃圾回收。
例程11-15 References.java
import java.lang.ref.*;
import java.util.*;
class Grocery{
private static final int SIZE = 10000;
//属性d使得每个Grocery对象占用较多内存,有80K左右
private double[] d = new double[SIZE];
private String id;
public Grocery(String id) { this.id = id; }
public String toString() { return id; }
public void finalize() {
System.out.println("Finalizing " + id);
}
}