您的位置:首页 > 编程语言 > Java开发

一个列子演示java中软引用的回收时机

2017-04-04 21:39 225 查看

示例代码如下:

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://gc.log




代码运行结果如下

[id=1,name=alexzanda]
After GC:
[id=1,name=alexzanda]
After a big object allocate:
null
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 软引用 gc