美文网首页JVM
21-垃圾回收相关概念

21-垃圾回收相关概念

作者: 紫荆秋雪_文 | 来源:发表于2021-06-07 08:52 被阅读0次

一、System.gc

  • 在默认情况下,通过System.gc() 或者 Runtime.getRuntime().gc()的调用,会显示触发"Full GC,同时对老年代和新生代"进行回收,尝试释放被丢弃对象占用的内存。
  • System.gc() 调用附带一个免责声明,无法保证对垃圾收集器的调用
  • JVM实现者可以通过 System.gc() 调用来决定JVM的GC行为。而一般情况下,垃圾回收应该是自动进行的,"无需手动触发,否则就太过于麻烦了"。在一些特殊情况下,如我们正在编写一个性能基准,我们可以在运行之间调用System.gc()

实例1

public class SystemGCTest {

    public void localvarGC1() {
        byte[] buffer = new byte[10 * 1024 * 1024]; // 10MB ( 10240k )
        System.gc();
    }

    public static void main(String[] args) {
        SystemGCTest gcTest = new SystemGCTest();
        gcTest.localvarGC2();
    }
}
  • 打印输出
[GC (System.gc()) [PSYoungGen: 12949K->503K(38400K)] 12949K->10751K(125952K), 0.0218291 secs] [Times: user=0.01 sys=0.00, real=0.02 secs] 
[Full GC (System.gc()) [PSYoungGen: 503K->0K(38400K)] [ParOldGen: 10248K->10683K(87552K)] 10751K->10683K(125952K), [Metaspace: 2937K->2937K(1056768K)], 0.0129399 secs] [Times: user=0.01 sys=0.01, real=0.02 secs] 
  • 从打印输出可知养老区的空间大小ParOldGen: 10248K->10683K,是大于10M的,所以System.gc并没有释放空间

实战2

public class SystemGCTest {

    public void localvarGC2() {
        byte[] buffer = new byte[10 * 1024 * 1024]; // 10MB
        buffer = null;
        System.gc();
    }

    public static void main(String[] args) {
        SystemGCTest gcTest = new SystemGCTest();
        gcTest.localvarGC2();
    }
}
  • 打印输出
[GC (System.gc()) [PSYoungGen: 12949K->567K(38400K)] 12949K->575K(125952K), 0.0012042 secs] [Times: user=0.00 sys=0.00, real=0.01 secs] 
[Full GC (System.gc()) [PSYoungGen: 567K->0K(38400K)] [ParOldGen: 8K->443K(87552K)] 575K->443K(125952K), [Metaspace: 2936K->2936K(1056768K)], 0.0166308 secs] [Times: user=0.01 sys=0.00, real=0.01 secs] 
  • 从打印输出可知,老年代ParOldGen: 8K->443K(87552K)小于10M,所以System.gc清理了空间

实战3

public class SystemGCTest {

    public void localvarGC3() {
        {
            byte[] buffer = new byte[10 * 1024 * 1024]; // 10MB
        }
        System.gc();
    }

    public static void main(String[] args) {
        SystemGCTest gcTest = new SystemGCTest();
        gcTest.localvarGC3();
    }
}
  • 打印输出
[GC (System.gc()) [PSYoungGen: 12949K->535K(38400K)] 12949K->10783K(125952K), 0.0232992 secs] [Times: user=0.01 sys=0.01, real=0.02 secs] 
[Full GC (System.gc()) [PSYoungGen: 535K->0K(38400K)] [ParOldGen: 10248K->10683K(87552K)] 10783K->10683K(125952K), [Metaspace: 2938K->2938K(1056768K)], 0.0095834 secs] [Times: user=0.01 sys=0.00, real=0.01 secs] 
  • 从打印输出的老年代可以发现并没有回收空间。更奇怪的问题是当buffer变量作用域很短,正常情况下已经没有应用对象了,问什么没有回收空间

实战4

public class SystemGCTest {
    public void localvarGC4() {
        {
            byte[] buffer = new byte[10 * 1024 * 1024]; // 10MB
        }
        int value = 10;
        System.gc();
    }

    public static void main(String[] args) {
        SystemGCTest gcTest = new SystemGCTest();
        gcTest.localvarGC4();
    }
}
  • 打印输出
[GC (System.gc()) [PSYoungGen: 12949K->503K(38400K)] 12949K->511K(125952K), 0.0030137 secs] [Times: user=0.01 sys=0.00, real=0.01 secs] 
[Full GC (System.gc()) [PSYoungGen: 503K->0K(38400K)] [ParOldGen: 8K->443K(87552K)] 511K->443K(125952K), [Metaspace: 2937K->2937K(1056768K)], 0.0269859 secs] [Times: user=0.00 sys=0.00, real=0.02 secs] 
  • 从打印可以空间被释放了,但是实战4和实战3唯一的区别就是在方法局部代码块之后又重新定义了一个局部变量

实战3字节码

字节码.png 局部变量最大槽数.png
本地局部变量表.png

实战4字节码

字节码.png 局部变量最大槽数.png 局部变量表.png
  • 小结
    • 代码中变量出了代码块变量销毁,但是变量所指向的内存空间,并不会被释放。所以可以理解为:在代码层面出了代码块之后变量被释放,而空间是否释放需要看字节码中是否执行该空间

二、内存溢出 与 内存泄露

1、内存溢出(OOM)
  • 内存溢出相对于内存泄露来说,尽管更容易被理解,但是同样的内存溢出也是引发程序崩溃的罪魁祸首之一

  • 由于GC一直在发展,所有一般情况下,除非应用程序占用的内存增长速度非常快,造成垃圾回收已经跟不上内存消耗的速度,否则不太容易出现OOM的情况

  • 大多数情况下,GC 会进行各种年龄段的垃圾回收,实在不行了就放大招,来一次独立式的 Full GC 操作,这时候会回收大量的内存,供应用程序继续使用

  • Javadoc中的OutOfMemoryError的解释是,没有空闲内存,并且垃圾收集器也无法提供更多内存

  • 没有空闲内存的情况,说明Java虚拟机的堆内存不够。原因有二

    • Java虚拟机的堆内存设置不高:可能存在内存泄露问题,也很有可能就是堆的大小不合理,比如我们要处理比较客观的数据量,但是没有显式指定JVM堆大小或者指定数组偏小。我们可以通过参数-Xms、-Xmx来调整
    • 代码中创建了大量大对象,并且长时间不能被垃圾收集器收集(存在被引用):对于老版本的Oracle JDK,因为永久代的大小是有限的,并且JVM对永久代垃圾回收(如:常量池回收、卸载不在需要的类型)非常不积极i,所以当我们不断添加新类型的时候,永久代出现OutOfMemoryError也非常多见,尤其是在运行时存在大量动态类型生成的场合;类似intern字符串缓存占用太多空间,也会导致OOM问题。对应的异常信息,会标记出来和永久代相关:"java.lang.OutOfMemoryError:PermGen space"。随着元数据的引入,方法区内存已经不再那么窘迫,所以相应的OOM有所改观,出现OOM,异常信息则变成了:"java.lang.OutOfMemoryError: Metaspace"。直接内存不足,也会导致OOM
  • 在抛出OutOfMemoryError之前,通常垃圾收集器会被触发,尽其所能去清理出空间

    • 例如:在引用机制分析中,涉及到JVM会去尝试回收 "软引用指向的对象等"
    • 在java.nio.Bits.reserveMemory()方法中,我们能清除的看到,System.gc()会被调用,以清理空间
  • 也不是在任何情况下垃圾收集器都会被触发

    • 比如,我们去分配一个超大对象,类似一个超大数组超过堆的最大值,JVM可以判断出垃圾收集并不能解决这个问题,所以直接抛出OutOfMemoryError
2、内存泄漏(Memory Leak)也称 存储渗漏
  • 定义:对象不会再被程序用到了,但是GC又不能回收他们的情况,才叫内存泄漏。
  • 内存泄漏情况
    • 情况1:单例模式中,单例的生命周期和应用程序是一样长的,所以单例程序中,如果持有对外部对象的引用的话,那么这个外部对象是不能被回收的,则会导致内存泄漏的产生
    • 情况2:一些提供 close 的资源未关闭导致内存泄漏。数据库连接(dataSource.getConnection),网络连接(socket)和 io 连接必须手动close,否则是不能被回收的

三、Stop The World

  • Stop The World,简称STW,指的是 GC 事件发生过程中,会产生应用程序的停顿。"停顿产生时整个应用程序线程都会被暂停,没有任何响应",有点像卡死的感觉,这个停顿称为STW。

  • 可达性分析算法中枚举根节点(GC Roots)会导致所有Java执行线程停顿。

    • 1、分析工作必须在一个能确保一致性的快照中进行
    • 2、一致性指整个分析期间整个执行系统看起来向被冻结在某个时间点上
    • 3、如果出现分析过程中对象引用关系还在不断变化,则分析结果的准确性无法保证
  • 被STW中断的应用程序线程会在完成 GC 之后恢复,频繁中断用户体验很差,所以我们需要减少STW的发生。

  • STW事件和采用哪款 GC 无关,所有的 GC 都有这个事件

  • 哪怕是 G1 也不能完全避免 Stop-The-World 情况发生,只能说垃圾回收器越来越优秀,回收效率越来越高,尽可能地缩短了暂停时间

  • STW是JVM在后台自动发起和自动完成的。在用户不可见的情况下,把用户正常的工作现场全部停掉

  • 开发中不要调用 System.gc();会导致 Stop-The-World的发生

测试Stop The World

  • 每秒输出

public class StopTheWorldTest {

    public static class PrintThread extends Thread {
        public final long startTime = System.currentTimeMillis();

        @Override
        public void run() {
            super.run();
            while (true) {
                long t = System.currentTimeMillis() - startTime;
                System.out.println(t / 1000 + "." + t % 1000);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        PrintThread printThread = new PrintThread();
        printThread.start();
    }
}
  • 打印输出
0.1
1.2
2.6
3.10
4.12
5.14
6.17
7.21
8.22
9.26
10.31
11.38
  • 调用GC

public class StopTheWorldTest {


    public static class StopTheWorldThread extends Thread {

        List<byte[]> list = new ArrayList<>();

        @Override
        public void run() {
            super.run();
            while (true) {

                for (int i = 0; i < 1000; i++) {
                    byte[] buffer = new byte[1024];
                    list.add(buffer);
                }

                if (list.size() > 10000) {
                    list.clear();
                    System.gc();
                }

            }
        }
    }

    public static class PrintThread extends Thread {
        public final long startTime = System.currentTimeMillis();

        @Override
        public void run() {
            super.run();
            while (true) {
                long t = System.currentTimeMillis() - startTime;
                System.out.println(t / 1000 + "." + t % 1000);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        StopTheWorldThread worldThread = new StopTheWorldThread();
        PrintThread printThread = new PrintThread();
        printThread.start();
        worldThread.start();
    }
}

四、垃圾回收的并行与并发

1、并发(Concurrent)

  • 在操作系统中,是指一个时间段中有几个程序都处于已启动运行到运行完毕之间,且这几个程序都是在同一个处理器上运行
  • 并发不是真正意义上的"同时进行",只是 CPU 把一个时间段划分成几个时间片段(时间区间),然后在这几个时间区间之间来回切换,由于 CPU 处理的速度非常快,只要时间间隔处理得当,即可让用户感觉是多个应用程序同时在进行 并发.png

2、并行(Parallel)

  • 当系统有一个以上 CPU 时,当一个 CPU 执行一个"进程"时,另一个 CPU 可以执行另一个进程,两个进程互不抢占 CPU 资源,可以同时进行,我们称之为并行。
  • 其实决定并行的因素不是 CPU 的数量,而是 CPU 的核心数量,比如一个 CPU 多个核也可以并行 image.png

3、并发与并行比较

  • 并发:指的是多个事情,在同一时间段内同时发生了,多个任务之间是相互抢占资源。
  • 并行:指的是多个事情,在同一时间点上同时发生了,多个任务之间是不相互抢占资源。

4、垃圾回收的并发与并行

  • 并发(Concurrent):指用户线程与垃圾收集线程同时执行(但不一定是并行的,可能会交替执行),垃圾回收线程在执行时不会停顿用户程序的运行。用户程序在继续运行,而垃圾收集程序运行于另一个 CPU 上(CMS 、G1)。 image.png
  • 并行(Parallel):指多条垃圾收集线程并行工作,但此时用户线程仍处于等待状态。(如:ParNew、Parallel Scavenge、Parallel Old)

  • 串行(Serial):相较于并行的概念,是单线程执行。如果内存不够,则程序暂停,启动JVM垃圾回收器进行垃圾回收。回收完,再启动程序的线程。 image.png

五、安全点与安全区域

1、安全点

程序执行时并非在所有地方都能停顿下来,开始 GC,只有在特定的位置才能停顿下来开始 GC,这些位置称为 "安全点(Safepoint)"。Safe Point 的选择很重要,如果太少可能导致 GC 等待的时间太长,如果太频繁可能导致运行时的性能问题。大部分指令的执行时间都非常短暂,通常会根据 "是否具有让程序长时间执行的特征" 为标准。如:选择一些执行时间较长的指令作为Safe Point,如方法调用、循环跳转和异常跳转等。

  • 如何在GC发生时,检查所有线程都跑到最近的安全点停顿下来
    • 方式一: 抢先式中断(目前没有虚拟机采用):首先中断所有线程。如果还有线程不在安全点,就恢复线程,让线程跑到安全点
    • 方式二: 主动式中断:设置一个中断标志,各个线程运行到 Safe Point的时候主动轮询这个标志,如果中断标志为真,则将自己进行中断挂起

2、安全区

SafePoint 机制保证了程序执行时,在不太长的时间内就会遇到可进入 GC 的SafePoint。但是程序 "不执行" 的时候?例如线程处于 Sleep 状态 或 Blocked 状态,这时候线程无法响应 JVM 的中断请求,"走到安全点"去中断挂起,JVM 也不太可能等待线程被唤醒。对于这种情况,就需要安全区域(Safe Region)来解决。

  • 安全区域:是指在一段代码片段中,对象的引用关系不会发生变化,在这个区域中的任何位置开始GC都是安全的。可以把 Safe Region 看做是被扩展的 Safe Point
  • 实际执行
    • 1、当线程运行到 Safe Region 的代码时,首先标识已经进入了 Safe Region,如果这段时间内发送GC,JVM会忽略标识为Safe Region状态的线程
    • 2、当线程即将离开Safe Region时,会检查 JVM 是否已经完成 GC ,如果完成了,则继续运行,否则线程必须等待直到收到可以安全离开Safe Region的信号为止。

六、引用

场景:当内存空间还足够时,则能保留在内存中;如果内存空间在进行垃圾收集后还是很紧张,则可以抛弃这些对象。为了满足这样的需求,在JDK1.2之后,Java对引用的概念进行了扩充,将引用分为强引用、软引用、弱引用、虚引用,这4种引用强度依次递减。

1、强引用(Strong Reference)

  • 可触及
  • 最常见的赋值引用,如:Object obj = new Object()
  • 无论任何情况下,只要强引用关系还存在,垃圾收集器就永远不会回收掉被引用的对象
  • 强引用也是造成内存溢出的根源

2、软引用(Soft Reference)

  • 软引用是用来描述一些还有用,但是非必须的对象。只被软引用关联着的对象在系统将要发生内存溢出异常前,会把这些对象列进回收范围之中进行第二次回收,如果这次回收还没有足够的内存,才会抛出内存溢出异常

  • 软可触及

  • 垃圾回收器在某个时刻决定回收软可达的对象的时候,会清理软引用,并可选的把引用存放到一个引用队列(Reference Queue)

  • 代码


/**
 * 软引用
 */
public class SoftReferenceTest {


    public static void main(String[] args) {
        // 创建软引用
        User user = new User(1, "Raven");
        SoftReference<User> softReference = new SoftReference<User>(user);
        // 取消强引用
        user = null;

        // 从软引用中获取引用对象
        System.out.println(softReference.get());
    }

    public static class User {

        public int id;
        public String name;

        public User(int id, String name) {
            this.id = id;
            this.name = name;
        }

        @Override
        public String toString() {
            return "[ id = " + id + " name = " + name + " ]";
        }
    }


}
  • 从软引用获取引用对象
public static void main(String[] args) {
        // 创建软引用
        User user = new User(1, "Raven");
        SoftReference<User> softReference = new SoftReference<User>(user);
        // 取消强引用
        user = null;

        // 从软引用中获取引用对象
        System.out.println(softReference.get());
    }
  • 打印输出
[ id = 1 name = Raven ]
  • GC之后获取软引用对象

    public static void main(String[] args) {
        // 创建软引用
        User user = new User(1, "Raven");
        SoftReference<User> softReference = new SoftReference<User>(user);
        // 取消强引用
        user = null;

        // 从软引用中获取引用对象
        System.out.println(softReference.get());

        // 手动触发 GC
        System.gc();
        System.out.println("GC 之后获取软引用对象:");
        System.out.println(softReference.get());
    }
  • 打印输出
[ id = 1 name = Raven ]
GC 之后获取软引用对象:
[ id = 1 name = Raven ]
  • 发现即使是 GC 了,依然可以获得软引用对象,这就说明软引用的对象并没有被回收,这是因为内存足够时并不会回收软引用指向的对象

  • 内存不足时


    public static void main(String[] args) {
        // 创建软引用
        User user = new User(1, "Raven");
        SoftReference<User> softReference = new SoftReference<User>(user);
        // 取消强引用
        user = null;

        // 从软引用中获取引用对象
        System.out.println(softReference.get());

        // 手动触发 GC
        System.gc();
        System.out.println("GC 之后获取软引用对象:");
        System.out.println(softReference.get());

        try {

            byte[] bytes = new byte[1024 * 1024 * 7];
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {

            System.out.println("内存紧张 之后获取软引用对象:");
            System.out.println(softReference.get());
        }

    }
  • 打印输出
[ id = 1 name = Raven ]
GC 之后获取软引用对象:
[ id = 1 name = Raven ]
内存紧张 之后获取软引用对象:
[ id = 1 name = Raven ]
  • 设置堆空间大小10m
-Xms10m -Xmx10m -XX:+PrintGCDetails
  • 打印输出
[ id = 1 name = Raven ]
[GC (System.gc()) [PSYoungGen: 1797K->503K(2560K)] 1797K->539K(9728K), 0.0129384 secs] [Times: user=0.00 sys=0.00, real=0.02 secs] 
[Full GC (System.gc()) [PSYoungGen: 503K->0K(2560K)] [ParOldGen: 36K->444K(7168K)] 539K->444K(9728K), [Metaspace: 2942K->2942K(1056768K)], 0.0174918 secs] [Times: user=0.01 sys=0.00, real=0.01 secs] 
GC 之后获取软引用对象:
[ id = 1 name = Raven ]
[GC (Allocation Failure) [PSYoungGen: 80K->64K(2560K)] 525K->508K(9728K), 0.0109678 secs] [Times: user=0.00 sys=0.00, real=0.02 secs] 
[GC (Allocation Failure) [PSYoungGen: 64K->32K(2560K)] 508K->476K(9728K), 0.0005738 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
[Full GC (Allocation Failure) [PSYoungGen: 32K->0K(2560K)] [ParOldGen: 444K->394K(7168K)] 476K->394K(9728K), [Metaspace: 2942K->2942K(1056768K)], 0.0127483 secs] [Times: user=0.00 sys=0.00, real=0.01 secs] 
[GC (Allocation Failure) [PSYoungGen: 0K->0K(2560K)] 394K->394K(9728K), 0.0004207 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
[Full GC (Allocation Failure) [PSYoungGen: 0K->0K(2560K)] [ParOldGen: 394K->378K(7168K)] 394K->378K(9728K), [Metaspace: 2942K->2942K(1056768K)], 0.0132753 secs] [Times: user=0.01 sys=0.00, real=0.01 secs] 
内存紧张 之后获取软引用对象:
null
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at com.lkty.reference.SoftReferenceTest.main(SoftReferenceTest.java:29)
Heap
 PSYoungGen      total 2560K, used 101K [0x00000007bfd00000, 0x00000007c0000000, 0x00000007c0000000)
  eden space 2048K, 4% used [0x00000007bfd00000,0x00000007bfd19738,0x00000007bff00000)
  from space 512K, 0% used [0x00000007bff80000,0x00000007bff80000,0x00000007c0000000)
  to   space 512K, 0% used [0x00000007bff00000,0x00000007bff00000,0x00000007bff80000)
 ParOldGen       total 7168K, used 378K [0x00000007bf600000, 0x00000007bfd00000, 0x00000007bfd00000)
  object space 7168K, 5% used [0x00000007bf600000,0x00000007bf65ebc0,0x00000007bfd00000)
 Metaspace       used 2973K, capacity 4556K, committed 4864K, reserved 1056768K
  class space    used 316K, capacity 392K, committed 512K, reserved 1048576K
Disconnected from the target VM, address: '127.0.0.1:62768', transport: 'socket'

Process finished with exit code 1

3、弱引用(Weak Reference)

  • 弱引用也是用来描述那些非必须对象,只被弱引用关联的对象只能生存到下一次垃圾收集发生为止。在系统GC时i,只要发现弱引用,不管系统堆空间使用是否充足,都会回收掉只被弱引用关联的对象

  • 弱引用对象与软引用对象的最大不同就在于,但GC在进行回收时,需要通过算法检查是否回收软引用对象,而对于弱引用对象,GC总是进行回收。弱引用对象更容易、更快被GC回收

  • 弱可触及

  • 弱引用测试代码


/**
 * 弱引用
 */
public class WeakReferenceTest {


    public static void main(String[] args) {
        // 创建软引用
        User user = new User(1, "Raven");
        WeakReference<User> weakReference = new WeakReference<User>(user);
        // 取消强引用
        user = null;

        // 从弱引用中获取引用对象
        System.out.println(weakReference.get());
    }

    public static class User {

        public int id;
        public String name;

        public User(int id, String name) {
            this.id = id;
            this.name = name;
        }

        @Override
        public String toString() {
            return "[ id = " + id + " name = " + name + " ]";
        }
    }


}
  • 打印输出
[ id = 1 name = Raven ]
Heap
 PSYoungGen      total 2560K, used 1839K [0x00000007bfd00000, 0x00000007c0000000, 0x00000007c0000000)
  eden space 2048K, 89% used [0x00000007bfd00000,0x00000007bfecbd88,0x00000007bff00000)
  from space 512K, 0% used [0x00000007bff80000,0x00000007bff80000,0x00000007c0000000)
  to   space 512K, 0% used [0x00000007bff00000,0x00000007bff00000,0x00000007bff80000)
 ParOldGen       total 7168K, used 0K [0x00000007bf600000, 0x00000007bfd00000, 0x00000007bfd00000)
  object space 7168K, 0% used [0x00000007bf600000,0x00000007bf600000,0x00000007bfd00000)
 Metaspace       used 2949K, capacity 4556K, committed 4864K, reserved 1056768K
  class space    used 313K, capacity 392K, committed 512K, reserved 1048576K
  • 手动GC
    public static void main(String[] args) {
        // 创建软引用
        User user = new User(1, "Raven");
        WeakReference<User> weakReference = new WeakReference<User>(user);
        // 取消强引用
        user = null;

        // 从弱引用中获取引用对象
        System.out.println(weakReference.get());
        // 手动触发 GC
        System.gc();
        System.out.println("GC 之后获取弱引用对象:");
        System.out.println(weakReference.get());
    }

  • 打印输出
[ id = 1 name = Raven ]
[GC (System.gc()) [PSYoungGen: 1798K->503K(2560K)] 1798K->539K(9728K), 0.0026733 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
[Full GC (System.gc()) [PSYoungGen: 503K->0K(2560K)] [ParOldGen: 36K->444K(7168K)] 539K->444K(9728K), [Metaspace: 2941K->2941K(1056768K)], 0.0166637 secs] [Times: user=0.01 sys=0.00, real=0.02 secs] 
GC 之后获取弱引用对象:
null
Heap
 PSYoungGen      total 2560K, used 101K [0x00000007bfd00000, 0x00000007c0000000, 0x00000007c0000000)
  eden space 2048K, 4% used [0x00000007bfd00000,0x00000007bfd19728,0x00000007bff00000)
  from space 512K, 0% used [0x00000007bff00000,0x00000007bff00000,0x00000007bff80000)
  to   space 512K, 0% used [0x00000007bff80000,0x00000007bff80000,0x00000007c0000000)
 ParOldGen       total 7168K, used 444K [0x00000007bf600000, 0x00000007bfd00000, 0x00000007bfd00000)
  object space 7168K, 6% used [0x00000007bf600000,0x00000007bf66f318,0x00000007bfd00000)
 Metaspace       used 2948K, capacity 4556K, committed 4864K, reserved 1056768K
  class space    used 313K, capacity 392K, committed 512K, reserved 1048576K

4、虚引用(Phantom Reference)

  • 也称"幽灵引用"或者"幻影引用",是所有引用类型中最弱的一个

  • 一个对象是否有虚引用的存在,完全不会对其生存时间构成影响,也无法通过虚引用来获得一个对象的实例。"为一个对象设置虚引用关联的唯一目的就是能在这个对象被收集器回收时收到一个系统通知"

  • 虚引用必须和引用队列一起使用。虚引用在创建时必须提供一个引用队列作为参数。当垃圾回收器准备回收一个对象时,如果发现它还有虚引用,就会在回收对象后,将这个虚引用加入引用队列,以通知应用程序对象的回收情况

  • 由于虚引用可以跟踪对象的回收时间,因此,也可以将一些资源释放操作放置在虚引用中执行和记录

  • 虚可触及

  • 虚引用代码测试


/**
 * 虚引用
 */
public class PhantomReferenceTest {

    public static PhantomReferenceTest obj;
    static ReferenceQueue<PhantomReferenceTest> phantomQueue = null;

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("调用" + PhantomReferenceTest.class + "类的 finalize方法");
    }

    public static void main(String[] args) {
        phantomQueue = new ReferenceQueue<>();
        obj = new PhantomReferenceTest();
        // 构造 PhantomReferenceTest 对象的虚引用,并指定了引用队列
        PhantomReference<PhantomReferenceTest> phantomReference = new PhantomReference<>(obj, phantomQueue);

        try {
            //  获取虚引用对象
            System.out.println("虚引用对象 = " + phantomReference.get());
        }
        catch (Exception e) {
            e.printStackTrace();
        }

    }
}
  • 打印输出
虚引用对象 = null
  • 手动触发 GC

    public static void main(String[] args) {
        phantomQueue = new ReferenceQueue<>();
        obj = new PhantomReferenceTest();
        // 构造 PhantomReferenceTest 对象的虚引用,并指定了引用队列
        PhantomReference<PhantomReferenceTest> phantomReference = new PhantomReference<>(obj, phantomQueue);

        try {
            //  获取虚引用对象
            System.out.println("虚引用对象 = " + phantomReference.get());

            // 将强引用设置null
            obj  = null;

            // 第1次手动GC
            System.gc();

            Thread.sleep(1000);
            if (null == obj) {
                System.out.println("obj 是 null");
            }
            else {
                System.out.println("obj 可用");
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
  • 打印输出
虚引用对象 = null
调用class com.lkty.reference.PhantomReferenceTest类的 finalize方法
obj 是 null
  • 第二次手动触发GC

    public static void main(String[] args) {
        phantomQueue = new ReferenceQueue<>();
        obj = new PhantomReferenceTest();
        // 构造 PhantomReferenceTest 对象的虚引用,并指定了引用队列
        PhantomReference<PhantomReferenceTest> phantomReference = new PhantomReference<>(obj, phantomQueue);

        try {
            //  获取虚引用对象
            System.out.println("虚引用对象 = " + phantomReference.get());

            // 将强引用设置null
            obj  = null;

            // 第1次手动GC
            System.gc();

            Thread.sleep(1000);
            if (null == obj) {
                System.out.println("obj 是 null");
            }
            else {
                System.out.println("obj 可用");
            }

            // 第2次手动GC
            System.out.println("第2次手动GC");
            obj  = null;
            System.gc();
            Thread.sleep(1000);
            if (null == obj) {
                System.out.println("obj 是 null");
            }
            else {
                System.out.println("obj 可用");
            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    
  • 打印输出
虚引用对象 = null
调用class com.lkty.reference.PhantomReferenceTest类的 finalize方法
obj 是 null
第2次手动GC
obj 是 null
  • 完整代码
package com.lkty.reference;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;

/**
 * 虚引用
 */
public class PhantomReferenceTest {

    public static PhantomReferenceTest obj;
    static ReferenceQueue<PhantomReferenceTest> phantomQueue = null;


    /**
     * 线程
     */
    public static class CheckRefQueue extends Thread {
        @Override
        public void run() {
            while (true) {
                if (null != phantomQueue) {
                    PhantomReference<PhantomReferenceTest> objt = null;
                    try {
                        objt = (PhantomReference<PhantomReferenceTest>) phantomQueue.remove();
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (null != objt) {
                        System.out.println("追踪垃圾回收过程: PhantomReferenceTest被GC了");
                    }
                }
            }
        }
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("调用" + PhantomReferenceTest.class + "类的 finalize方法");
    }

    public static void main(String[] args) {

        CheckRefQueue refQueue = new CheckRefQueue();
        // 设置为守护线程
        refQueue.setDaemon(true);
        refQueue.start();

        phantomQueue = new ReferenceQueue<>();
        obj = new PhantomReferenceTest();
        // 构造 PhantomReferenceTest 对象的虚引用,并指定了引用队列
        PhantomReference<PhantomReferenceTest> phantomReference = new PhantomReference<>(obj, phantomQueue);

        try {
            //  获取虚引用对象
            System.out.println("虚引用对象 = " + phantomReference.get());

            // 将强引用设置null
            obj = null;

            // 第1次手动GC
            System.gc();

            Thread.sleep(1000);
            if (null == obj) {
                System.out.println("obj 是 null");
            } else {
                System.out.println("obj 可用");
            }

            // 第2次手动GC
            System.out.println("第2次手动GC");
            obj = null;
            System.gc();
            Thread.sleep(1000);
            if (null == obj) {
                System.out.println("obj 是 null");
            } else {
                System.out.println("obj 可用");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
  • 打印输出
Connected to the target VM, address: '127.0.0.1:55408', transport: 'socket'
虚引用对象 = null
调用class com.lkty.reference.PhantomReferenceTest类的 finalize方法
obj 是 null
第2次手动GC
追踪垃圾回收过程: PhantomReferenceTest被GC了
obj 是 null
Disconnected from the target VM, address: '127.0.0.1:55408', transport: 'socket'

5、终结器引用

  • 它用以实现对象的 finalize()方法,也可以称为终结器引用
  • 无需手动编码,其内部配合引用队列使用
  • 在GC时,终结器引用入队。由Finalizer线程通过终结器引用找到被引用对象并调用它的finalize()方法,第二次GC时才能回收被引用对象

相关文章

网友评论

    本文标题:21-垃圾回收相关概念

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