JAVA Object References in JVM--Soft References

软引用(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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值