示例代码如下:
import java.lang.ref.SoftReference;
/**
* 软引用比弱引用强,如果一个对象只有软引用,那么当堆空间不足时候,才会被回收
* 该类用于演示软引用的这一性质
* 2017年4月4日 下午9:30:38
* @version v1.0
*/
public class SoftRef
{
public static class Student
{
public int id;
public String name;
public Student(Integer id, String name)
{
this.id = id;
this.name = name;
}
@Override
public String toString()
{
return "[id=" + id + ",name=" + name + "]";
}
}
public static void main(String... args) throws InterruptedException
{
Student u = new Student(1, "alexzanda");
SoftReference<Student> studentSoftRef = new SoftReference<Student>(u);
u = null;
System.out.println(studentSoftRef.get());
System.gc();
System.out.println("After GC:");
System.out.println(studentSoftRef.get());
System.out.println("After a big object allocate:");
byte[] b = new byte[1024 * 925 * 7];
System.gc();
System.out.println(studentSoftRef.get());
}
}
本人是通过eclipse来运行该段代码的,在运行代码前,设置了如下虚拟机参数:
-Xmx10m -XX:+PrintGC -XX:+PrintGCDetails -XX:+PrintHeapAtGC -Xloggc:d:
代码运行结果如下
[id=1,name=alexzanda]
After GC:
[id=1,name=alexzanda]
After a big object allocate:
null