弱引用(Weak References)只具有弱引用的对象拥有更短暂的生命周期。在垃圾回收器线程扫描它所管辖的内存区域的过程中,一旦发现了只具有弱引用的对象,不管当前内存空间足够与否,一概回收。不过,由于垃圾回收期是一个优先级很低的线程,所以不一定能执行。
弱引用可以和一个引用队列(Reference Queue)联合使用,如果弱引用所引用的对象被垃圾回收,JVM就会把这个弱引用加入到与之关联的引用队列中。
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
/*
* A sample for Detecting and locating memory leaks in Java
* URL: http://neverfear.org/blog/view/150/Java_References
* Author: [email protected]
*/
publicclass ClassWeak {
publicstaticclass Referred {
protectedvoid finalize() {
System.out.println("Good bye cruel world");
}
}
publicstaticvoid collect() throws InterruptedException {
System.out.println("Suggesting collection");
System.gc();
System.out.println("Sleeping");
Thread.sleep(5000);
}
publicstaticvoid main(String args[]) throws InterruptedException {
System.out.println("Creating weak references");
// This is now a weak reference.
// The object will be collected only if no strong references.
Referred strong = new Referred();
WeakReference<Referred> weak = new WeakReference<Referred>(strong);
System.out.println("weak="+weak);
// Attempt to claim a suggested reference.
ClassWeak.collect();
System.out.println("weak="+weak);
System.out.println("Removing reference");
// The object may be collected.
strong = null;
weak = null;
System.out.println("weak="+weak);
ClassWeak.collect();
System.out.println("weak="+weak);
System.out.println("Done");
}
}
Output:
Creating weak references
weak=java.lang.ref.WeakReference@a90653
Suggesting collection
Sleeping
weak=java.lang.ref.WeakReference@a90653
Removing reference
weak=null
Suggesting collection
Sleeping
Good bye cruel world
weak=null
Done