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

示例代码如下:


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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值