软引用(soft references)只要垃圾回收器没有回收它,该对象就可以被程序使用。软引用可用来实现内存敏感的高速缓存。软引用可以和一个引用队列(Reference Queue)联合使用,如果软引用所引用的对象被垃圾回收器回收,JVM就会把这个软引用加入到与之关联的引用队列中。
import java.lang.ref.SoftReference;
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: doug@neverfear.org
*/
publicclass ClassSoft {
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 soft references");
// This is now a soft reference.
// The object will be collected only if no strong references exist and the JVM really needs the memory.
Referred strong = new Referred();
SoftReference<Referred> soft = new SoftReference<Referred>(strong);
System.out.println("soft="+soft);
//soft=null;
// Attempt to claim a suggested reference.
ClassSoft.collect();
System.out.println("soft="+soft);
System.out.println("Removing reference");
// The object may but highly likely wont be collected.
strong = null;
ClassSoft.collect();
System.out.println("soft="+soft);
System.out.println("Consuming heap");
try
{
// Create lots of objects on the heap
List<ClassSoft> heap = new ArrayList<ClassSoft>(100000);
while(true) {
heap.add(new ClassSoft());
}
}
catch (OutOfMemoryError e) {
// The soft object should have been collected before this
System.out.println("Out of memory error raised");
System.out.println("soft="+soft);
}
System.out.println("Done");
}
}
Output:
Creating soft references
soft=java.lang.ref.SoftReference@a90653
Suggesting collection
Sleeping
soft=java.lang.ref.SoftReference@a90653
Removing reference
Suggesting collection
Sleeping
soft=java.lang.ref.SoftReference@a90653
Consuming heap
Good bye cruel world
Out of memory error raised
soft=java.lang.ref.SoftReference@a90653
Done