美文网首页
Java中的四种引用类型

Java中的四种引用类型

作者: LeonardoEzio | 来源:发表于2019-04-28 18:03 被阅读0次

    1. 概述

    Java虚拟机垃圾收集这一文中,我们谈到了Java中对引用的定义有如下四种:强引用,软引用,弱引用,虚引用四种。接下来我们就具体谈一谈这四种引用。

    Java中的引用类型.png

    2. 强引用

    Java语言通过引用使得我们可以直接操作堆中的对象,下例中的变量str指向String实例所在的堆空间,通过str我们可以操作该对象

    String str = new String("StrongReference");
    

    强引用具有如下的特点:

    1. 可以直接访问目标对象
    2. 所指向的对象在任何时候都不会被系统回收,JVM宁愿抛出OOM异常,也不会回收强引用所指向的对象
    3. 可能会导致内存泄漏

    3. 软引用

    软引用是除了强引用外最强的引用类型,我们可以通过java.lang.ref.SoftReference来使用软引用。SoftReference实例可以保存对一个Java对象的软引用,在不妨碍垃圾收集器对该Java对象进行回收的前提下,也就是在该对象被垃圾回收器回收之前,通过SoftReference类的get()方法可以获得该Java对象的强引用,一旦该对象被回收之后,get()就会返回null。

    /**jvm参数 :-XX:+PrintGCDetails -Xmx4m -Xms4m -Xmn4m */
    public class ReferenceTest {
        public static void main(String[] args) {
            byte[] byte1 = new byte[1024 * 515];
            SoftReference softReference = new SoftReference(byte1);
            byte1 = null;
            System.gc();
            System.out.println("obj 是否被回收 ? "+softReference.get());
        }
    }
    /********************************************************************************************/
    /**
    obj 是否被回收 ? [B@7cd84586
    Heap
     PSYoungGen      total 3072K, used 1108K [0x00000000ffc80000, 0x0000000100000000, 0x0000000100000000)
      eden space 2560K, 43% used [0x00000000ffc80000,0x00000000ffd952a8,0x00000000fff00000)
      from space 512K, 0% used [0x00000000fff80000,0x00000000fff80000,0x0000000100000000)
      to   space 512K, 0% used [0x00000000fff00000,0x00000000fff00000,0x00000000fff80000)
     ParOldGen       total 512K, used 454K [0x00000000ffc00000, 0x00000000ffc80000, 0x00000000ffc80000)
      object space 512K, 88% used [0x00000000ffc00000,0x00000000ffc71898,0x00000000ffc80000)
     Metaspace       used 3231K, capacity 4496K, committed 4864K, reserved 1056768K
      class space    used 352K, capacity 388K, committed 512K, reserved 1048576K
    Java HotSpot(TM) 64-Bit Server VM warning: MaxNewSize (4096k) is equal to or greater than the entire heap (4096k).  A new max generation size of 3584k will be used.
    */
    

    这是虽然进行了一次GC但是通过软引用还是能取得对象,接下来我们再申请一块大一点的空间

    public class ReferenceTest {
        public static void main(String[] args) {
            byte[] byte1 = new byte[1024 * 515];
            SoftReference softReference = new SoftReference(byte1);
            byte1 = null;
            System.gc();
            byte[] byte2 = new byte[1024 * 2500];
            System.out.println("obj 是否被回收 ? "+softReference.get());
        }
    }
    /**********************************************************************************************/
    /**
    obj 是否被回收 ? null
    [Full GC (Ergonomics) [PSYoungGen: 2560K->0K(3072K)] [ParOldGen: 467K->464K(512K)] 3027K->464K(3584K), [Metaspace: 3313K->3313K(1056768K)], 0.0056548 secs] [Times: user=0.00 sys=0.00, real=0.01 secs] 
    Heap
     PSYoungGen      total 3072K, used 25K [0x00000000ffc80000, 0x0000000100000000, 0x0000000100000000)
      eden space 2560K, 1% used [0x00000000ffc80000,0x00000000ffc867f0,0x00000000fff00000)
      from space 512K, 0% used [0x00000000fff80000,0x00000000fff80000,0x0000000100000000)
      to   space 512K, 85% used [0x00000000fff00000,0x00000000fff6ce98,0x00000000fff80000)
     ParOldGen       total 512K, used 464K [0x00000000ffc00000, 0x00000000ffc80000, 0x00000000ffc80000)
      object space 512K, 90% used [0x00000000ffc00000,0x00000000ffc74198,0x00000000ffc80000)
     Metaspace       used 3319K, capacity 4496K, committed 4864K, reserved 1056768K
      class space    used 359K, capacity 388K, committed 512K, reserved 1048576K
    */
    

    此时,PSYoungGen(年轻代)中的2560K空间肯定是不够用的,就会触发一次垃圾回收,当然你也可以显示的再调用一次gc(),经过这次GC后软引用已经被回收了。因此我们可以总结出软引用有如下特点:

    1. 一个持软引用的对象,不会立马被垃圾回收器所回收。
    2. 当堆内存的使用率接近阈值时,才会去回收软引用的对象。

    4. 弱引用

    弱引用是一种比软引用还要弱的引用类型。在系统进行GC的时候,只要发现弱引用都会对其进行回收。我们可以通过java.lang.ref.WeakReference来保存一个弱引用的实例。

    public class ReferenceTest {
        public static void main(String[] args) {
            byte[] byte1 = new byte[1024 * 515];
            WeakReference<byte[]> weakReference = new WeakReference<>(byte1);
            byte1 = null;
            System.out.println("弱引用是否被回收 : "+weakReference.get());
            System.gc();
            System.out.println("弱引用是否被回收 : "+weakReference.get());
        }
    }
    /**********************************************************************************************/
    /**
    弱引用是否被回收 : [B@7cd84586
    弱引用是否被回收 : null
    */
    

    5. 虚引用

    虚引用是所有引用类型中最弱的一种,一个持有虚引用的对象和几乎没有引用是一样的,随时可能被垃圾回收器所回收。虚引用的get方法总是会返回null。为了追踪垃圾回收过程,虚引用必须和引用队列一起使用。

    public class ReferenceTest {
        public static void main(String[] args) {
            byte[] byte1 = new byte[1024 * 515];
            ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
            PhantomReference sf = new PhantomReference<>(byte1,referenceQueue);
            byte1 = null;
            System.out.println("是否被回收"+sf.get());
            System.gc();
            System.out.println("是否被回收"+sf.get());
        }
    }
    /*********************************************************************************************/
    /**
    是否被回收null
    是否被回收null
    */
    

    6. WeakHashMap

    WeakHashMap类属于java.util包,实现了Map接口,是HashMap的一种实现,使用弱引用作为内部数据的存储方案。

    /** -Xmx4m -Xms4m -Xmn4m  限定堆栈空间大小为4M*/
    public class ReferenceTest {
        public static void main(String[] args) {
    //        WeakHashMap<Object, Object> weakMap = new WeakHashMap<>();
    //        for (int i = 0 ; i<10000000; i++){
    //            weakMap.put(i, new byte[i]);
    //        }
    
            HashMap<Object, Object> hashMap = new HashMap<>();
            for (int i = 0 ; i<10000000; i++){
                hashMap.put(i, new byte[i]);
            }
        }
    }
    

    通过结果我们可以发现,使用WeakHashMap的代码可以正常运行结束,而使用HashMap的代码则会抛出OOM异常,因为WeakHashMap会在内存使用紧张时使用弱引用,自动释放掉持有弱引用的内存数据,但是如果WeakHashMap的key都在系统里持有强引用,那么WeakHashMap就会跟普通的HashMap一样,里面的数据无法被自动清理。

    相关文章

      网友评论

          本文标题:Java中的四种引用类型

          本文链接:https://www.haomeiwen.com/subject/avpjnqtx.html