Java中的强软弱虚

    从JDK1.2版本开始,把对象引用分别四中级别,从而使程序能更加灵活的控制对象的生命周期,四中级别由高到低依次为:强引用、软引用、弱引用和虚引用。

1、强引用:

    比如 Object object=new Object(); new 创建出来的object 对象就是强引用。当内存空间不足时,Java虚拟机宁愿抛出OutOfMemoryError错误,是程序异常终止,也不会靠随意回收具有强引用的对象来解决内存不足的问题。

2、软引用(SoftReference):

    如果一个对象是软引用,如果内存空间足够,垃圾回收器就不会回收它,如果内存空间不足了,就会回收这些对象的内存。只要垃圾回收器没有回收它,该对象就可以被程序使用。软引用可以用来实现内存敏感的高速缓存。软引用可以和一个引用队列(ReferenceQueue)联合使用,如果软引用所引用的对象被垃圾回收,Java虚拟机就会把这个软引用加入到与之关联的引用队列中。

3、弱引用(WeakReference):

    弱引用和软引用的区别在于:只具有弱引用的对象拥有更短暂的生命周期。在垃圾回收器线程扫描它所管辖的内容区域的过程中,一旦发现了只具有弱引用对象,不管当前内存空间足够与否,都会回收它的内存。不过,由于垃圾回收器是一个优先级很低的线程,因此不一定会很快发现那些具有弱引用的对象。弱引用可以和一个引用队列(ReferenceQueue)联合使用,如果弱引用所引用的对象被垃圾回收,Java虚拟机就会把这个弱引用加入到与之关联的引用队列中。

4、虚引用(PhantomReference):

    “虚引用”顾名思义,就是形同虚设的意思,与其他几种引用都不同,虚引用并不会决定对象的生命周期。如果一个对象仅持有虚引用,那么它就和没有任何引用一样,在任何时候都可能被垃圾回收。虚引用主要用来跟踪对象被垃圾回收的活动。虚引用与软引用和弱引用的一个区别在于:虚引用必须和引用队列(ReferenceQueue)联合使用。当垃圾回收器准备回收一个对象时,如果发现它还有虚引用,就会在回收对象的内存之前,把这个虚引用加入到与之关联的引用队列中。程序可以通过判断引用队列中是否已经加入了虚引用,来了解被引用的对象是否将要被垃圾回收。程序如果发现某个虚引用已经被加入到引用队列,那么就可以在所引用的对象的内存被回收之前采取必要的行动。

5、相关应用

    在java.lang.ref包中提供了三个类:SoftReference类、WeakReference类和PhantomReference类,它分别代表软引用、弱引用和虚引用。ReferenceQueue类表示引用队列,它可以和这三种引用类联合使用,以便跟踪Java虚拟机回收所引用的对象的活动。

    1)先看一段代码

//创建一个强引用
String str=new String("hello");//1
//创建引用队列;表明队列中存放String对象的引用ReferenceQueue;
ReferenceQueue rq=new ReferenceQueue();//2
//创建一个弱引用,它引用"hello"对象,并且与rq引用队列关联 表明WeakReference会弱引用String对象
WeakReference wf=new WeakReference(str,rq);//3

  以上代码执行完毕,内存中引用与对象的关系如图所示:


                        图1   “hello” 对象同时具有强引用和弱引用

   上图中实线表示强引用,虚线表示弱引用。由图看出,"hello"对象被str强引用,并且被一个WeakReference弱引用,因此“hello”对象不会被垃圾回收。

    2)在以下程序代码中,把引用“hello”对象变量设置为null,然后再通过WeakReference弱引用的get()方法获得“hello”对象的引用:

String str=new String("hello");//1
//创建引用队列;表明队列中存放String对象的引用ReferenceQueue;
ReferenceQueue rq=new ReferenceQueue();//2
//创建一个弱引用,它引用"hello"对象,并且与rq引用队列关联 表明WeakReference会弱引用String对象
WeakReference wf=new WeakReference(str,rq);//3
str=null;//4 取消"hello" 对象的强引用
String str1= (String) wf.get();//5 假如“hello”对象没有被回收,str1引用“hello”对象;
// 假如“hello”对象没有被回收,rq.poll()返回null
Reference ref=rq.poll();//6
执行完第四行后,内存中引用与对象的关系如下图所示:


    图2 “hello”对象仅仅具有弱引用

因此他有可能会被垃圾回收。假如他还没有被垃圾回收,那么接下来第5行代码执行wf.get()方法会返回“hello”对象的引用,并且使得对象被强引用。在接下来第6行执行rq.poll() 方法会返回null,因为此时引用中没有任何引用。ReferenceQueue的poll()方法用于返回队列中的引用,如果没有则返回null。

    3)先看代码

//创建一个强引用
String str=new String("hello");//1
//创建引用队列;表明队列中存放String对象的引用ReferenceQueue;
ReferenceQueue rq=new ReferenceQueue();//2
//创建一个弱引用,它引用"hello"对象,并且与rq引用队列关联 表明WeakReference会弱引用String对象
WeakReference wf=new WeakReference(str,rq);//3
str=null;//4 取消"hello" 对象的强引用
//两次催促垃圾回收器工作,提高“hello”对象被回收的可能
System.gc();//5
System.gc();//6
String str1= (String) wf.get();//7 假如“hello”对象没有被回收,str1引用“hello”对象;
// 假如“hello”对象没有被回收,rq.poll()返回null
Reference ref=rq.poll();//8

在以上程序代码中,在执行完第4行代码后,“hello”对象仅仅具有弱引用。接下来两次调用System.gc()方法,催促垃圾回收器工作,从而提高“hello” 对象被回收的可能性。假如“hello”对象被回收,那么WeakReference对象的引用被加入到ReferenceQueue中,接下来wf.get()方法返回null,并且rq.poll()方法返回WeakReference对象的引用。图3显示执行了第8行代码后内存中引用与对象的关系。


    图3 "hello" 对象被垃圾回收,弱引用被加入到引用队列


    4)继续先看代码

package com.lixm.animationdemo.bean;

import org.xutils.common.util.LogUtil;

/**
 * Describe:
 * <p>
 *     强软弱虚创建对象
 *
 * Author: Lixm
 * Date: 2018/6/27
 */
public class Grocery {
    private String TAG=getClass().getName();
    private static final int SIZE=10000;
    //属性d使得每个Grocery对象占用较多的内存,有80k左右
    private double[] d=new double[SIZE];
    private String id;

    public Grocery(String id) {
        this.id = id;
    }

    public String toString(){
        return id;
    }

    public void finalize(){
        LogUtil.i(TAG,"Finalizing "+id);
    }
}
/**
 * Describe:
 * <p>
 * 强软弱虚创建对象
 * Author: Lixm
 * Date: 2018/6/27
 */
public class References {
    private static String TAG = "References";

    private static ReferenceQueue rq = new ReferenceQueue();

    public static void checkQueue() {
        Reference inq = rq.poll();
        //从队列中取出一个引用
        if (inq != null) {
            LogUtil.i(TAG, "In queue: " + inq + " : " + inq.get());
        }
    }

    public static void main(String[] args) {
        final int size = 10;
        //创建10Grocery对象,以及10个软引用
        Set sa = new HashSet();
        for (int i = 0; i < size; i++) {
            SoftReference ref = new SoftReference(new Grocery("soft" + i), rq);
            LogUtil.i(TAG, "Just created soft: " + ref.get());
            sa.add(ref);
        }
        System.gc();
        checkQueue();

        LogUtil.i(TAG,"---------------------------------");
        //创建10Grocery对象以及10个弱引用
        Set wa=new HashSet();
        for (int i=0;i<size;i++){
            WeakReference ref=new WeakReference(new Grocery("weak"+i),rq);
            LogUtil.i(TAG,"Just created weak: "+ref.get());
            wa.add(ref);
        }
        System.gc();
        checkQueue();

        System.out.println("=============================");
        //创建10Grocery对象,以及10个虚引用
        Set pa=new HashSet();
        for (int i=0;i<size;i++){
            PhantomReference ref=new PhantomReference(new Grocery("Phantom "+i),rq);
            System.out.println("Just created Phantom :"+ref.get());
            pa.add(ref);
        }
        System.gc();
        checkQueue();
    }
}
 

打印结果为:

Just created soft: soft0Just created soft: soft1Just created soft: soft2Just created soft: soft3Just created soft: soft4Just created soft: soft5Just created soft: soft6Just created soft: soft7Just created soft: soft8Just created soft: soft9---------------------------------Just created weak: weak0Just created weak: weak1Just created weak: weak2Just created weak: weak3Just created weak: weak4Just created weak: weak5Just created weak: weak6Just created weak: weak7Just created weak: weak8Just created weak: weak9-----------------------------------------------Finalizing weak9Finalizing weak8Finalizing weak6Just created Phantom :nullFinalizing weak7Just created Phantom :nullFinalizing weak0Finalizing weak1Just created Phantom :nullFinalizing weak4Finalizing weak5Just created Phantom :nullFinalizing weak2Just created Phantom :nullJust created Phantom :nullFinalizing weak3Just created Phantom :nullJust created Phantom :nullJust created Phantom :nullJust created Phantom :nullFinalizing Phantom 4Finalizing Phantom 2Finalizing Phantom 1Finalizing Phantom 3Finalizing Phantom 6Finalizing Phantom 5Finalizing Phantom 7Finalizing Phantom 9Finalizing Phantom 8Finalizing Phantom 0In queue: java.lang.ref.WeakReference@232204a1 : null

在以上References类中,依次创建了10个软引用,10个弱引用和10个虚引用,他们各自引用一个Grocery对象。从程序运行时打印的结果可以看出,虚引用形同虚设,他所引用的对象随时可能被垃圾回收;具有弱引用的对象拥有稍长的生命周期,当垃圾回收器执行回收操作时,有可能被垃圾回收;具有软引用的对象拥有较长的生命周期,但在Java虚拟机认为内容不足的情况下,也会被垃圾回收。

5)在Java集合中有一种特殊的Map类型:WeakHashMap,在这种Map中存放了键对象的弱引用,当一个键对象被垃圾回收,那么相应的值对象的引用会从Map中删除。WeakHashMap能够节约存储空间,可用来缓存那些非必须存放的数据。

    以下代码MapCache类的main()方法创建了一个WeakHashMap对象,它存放了一组Key对象的弱引用,此外main()方法还创建了一个数组对象,它存放了部分key对象的强引用。

package com.lixm.animationdemo.bean;

/**
 * Describe:
 * <p>
 * Author: Lixm
 * Date: 2018/6/27
 */
public class Key {
    private String id;

    public Key(String id) {
        this.id = id;
    }

    public String toString (){
        return id;
    }

    public int hashCode(){
        return id.hashCode();
    }

    public boolean equals(Object r){
        return (r instanceof Key) && id.equals(((Key)r).id);
    }
}
package com.lixm.animationdemo.bean;

/**
 * Describe:
 * <p>
 * Author: Lixm
 * Date: 2018/6/27
 */
public class Value {
    private String id;

    public Value(String id) {
        this.id = id;
    }

    public String toString() {
        return id;
    }

    public void finalize() {
        System.out.println("Finalizing Value " + id);
    }
}
package com.lixm.animationdemo.bean;

import java.util.Scanner;
import java.util.WeakHashMap;

/**
 * Describe:
 * <p>
 * Author: Lixm
 * Date: 2018/6/27
 */
public class MapCache {
    public static void main(String[] args)throws Exception{
//        int size=1000;//或者从命令行获得Size的大小
        System.out.println("请输入size大小:");
        Scanner sc=new Scanner(System.in);
        String sizeStr=sc.next();
        int size=Integer.parseInt(sizeStr);
        if (args.length>0) {
            size = Integer.parseInt(args[0]);
        }
        Key[] keys=new Key[size];//存放键对象的强引用
        WeakHashMap whm=new WeakHashMap();
        for (int i=0;i<size;i++){
            Key k=new Key(Integer.toString(i));
            Value v=new Value(Integer.toString(i));
            if (i%3==0){
                keys[i]=k;//使key对象持有强引用
            }
            whm.put(k,v);//key对象持有弱引用
        }
        //催促垃圾回收器工作
        System.gc();//CPU让给垃圾回收器线程
        Thread.sleep(8000);
    }
}

打印结果为:

Finalizing Key 82
Finalizing Key 7
Finalizing Key 5
Finalizing Key 4
Finalizing Key 2
Finalizing Key 1
Finalizing Key 20
Finalizing Key 19
Finalizing Key 17
Finalizing Key 16
Finalizing Key 14
Finalizing Key 13
Finalizing Key 11
Finalizing Key 10
Finalizing Key 8
Finalizing Key 34
Finalizing Key 32
Finalizing Key 31
Finalizing Key 29
Finalizing Key 28
Finalizing Key 26
Finalizing Key 25
Finalizing Key 23
Finalizing Key 22
Finalizing Key 98
Finalizing Key 97
Finalizing Key 95
Finalizing Key 94
Finalizing Key 92
Finalizing Key 91
Finalizing Key 89
Finalizing Key 88
Finalizing Key 47
Finalizing Key 46
Finalizing Key 44
Finalizing Key 43
Finalizing Key 41
Finalizing Key 40
Finalizing Key 38
Finalizing Key 37
Finalizing Key 35
Finalizing Key 61
Finalizing Key 59
Finalizing Key 58
Finalizing Key 56
Finalizing Key 55
Finalizing Key 53
Finalizing Key 52
Finalizing Key 50
Finalizing Key 49
Finalizing Key 74
Finalizing Key 73
Finalizing Key 71
Finalizing Key 70
Finalizing Key 68
Finalizing Key 67
Finalizing Key 65
Finalizing Key 64
Finalizing Key 62
Finalizing Key 86
Finalizing Key 85
Finalizing Key 83
Finalizing Key 80
Finalizing Key 79
Finalizing Key 77

Finalizing Key 76

从打印结果看出,当执行System.gc()方法后,垃圾回收器只会回收那么仅仅持有弱引用的Key对象。id可以被3整除的key对象持有强引用,因此不会被回收。

6、如何使用软引用

SoftReference的特点是他的一个实例保存对一个Java对象的软引用,该软引用的存在不妨碍垃圾收集线程对该Java对象的回收,也就是说,一旦SoftReference保存了对一个Java对象的软引用后,在垃圾线程对这个Java对象回收前,SoftReference类所提供的get()方法返回Java对象的强引用。另外,一旦垃圾线程回收该Java对象只有,get方法将返回null。

Grocery grocery=new Grocery("Soft");
SoftReference aSoft=new SoftReference(grocery);

此时对于Grocery对象,有两个引用路径,一个是来自SoftReference对象的软引用,一个来自变量aReference的强引用,所以这个Grocery对象是强引用对象。

随即,我们可以结束aReference对这个Grocery实例的强引用:

grocery=null;

在回收这些对象之前,我们可以通过:

Grocery anotherRef=(Grocery) aSoft.get();

重新获得对该实例的强引用。而回收之后,调用get()方法就只能得到null了。清除SoftReference对象:  

SoftReference ref=null;
while((ref =  (SoftReference) rq.poll()) != null) {
    //清除ref
}

熟悉了解了ReferenceQueue的工作机制之后,我们就可以开始构造一个Java对象的告诉缓存器了。

    7、用WeakHashMap堵住泄露

    在SocketManager中防止泄露很容易,只要用WeakHashMap代替HashMap就行了。(这里假定SocketManager不需要线程安全)。当映射的生命周期必须与键的生命期联系在一起时,可以使用这种方法,用WeakHashMap修复SocketManager。

/**
 * Describe:
 * <p>
 * Author: Lixm
 * Date: 2018/6/27
 */
public class SocketManager {
    private Map m=new WeakHashMap();
    public void setUser(Socket s,User u){
        m.put(s,u);
    }
    public User getUser(Socket s){
        return (User) m.get(s);
    }
}

至此,大致了解了Java中的强软弱虚引用,选择合适的引用,已完成更高效的程序开发。

本文参考:点击打开链接 谢谢

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值