Knowledge Summary: garbage collection (manually let the JVM garbage collection to do with Runtime.getRuntime () gc () or System.gc ().); Final, finally, finalize the difference between the three

Knowledge Summary: 1 by manually make do jvm garbage collection, with Runtime.getRuntime () gc () or System.gc (); 2 final, finally, finalize the difference between the three....

/**
 * @author yyh on 2020/3/31 20:12
 */
public class ObjectClassExercise{//所有类都是继承 extends Object(一般没写,但其实是有的)
    static class People{
        private String name;
        private int age;
        private char gender;

        public People(String name, int age, char gender) {
            this.name = name;
            this.age = age;
            this.gender = gender;
        }

        @Override//重写父类finalize()方法
        protected void finalize() throws Throwable {
            super.finalize();//默认父类此方法是空实现
            System.out.println("--------------------");
            System.out.println("被调用了嘛?");
            System.out.println("--------------------");
        }
    }

    public static void main(String[] args) {
          /*
       		垃圾回收GC:
            通过手动方式让JVM做垃圾回收Garbage Collector有以下2种方式:
            a)	Runtime.getRuntime().gc():运行垃圾回收器。
            b)	System.gc():运行垃圾回收器。

           在JVM Garbage Collector回收对象之前JVM会去调用Object.finalize()方法,
           当我们重写finalize()方法后,在jvm调用该方法时,用户就可以手动释放一些对象占用的系统级资源。

           JDK有多种:
            1. Oracle JDK
            2. Open JDK
            3. GitHub - alibaba/dragonwell8: Alibaba Dragonwell8 JDK:
                https://github.com/alibaba/dragonwell8

            final, finally, finalize三者间的区别:
            1. final,声明类即不能继承; 声明方法不能被子类重写;声明变量即为常量;声明参数即不能重新赋值;
            2. finally, 是用于异常处理中的代码块, 跟在try或catch代码块后
                try{
                    ......
                } finally{
                }

                try{
                    ......
                } catch(Exception e){
                }finally{
                }
            3. finalize()是Object类中的方法,用于在gc时由JVM自动去调用
        */
        People kk = new People("kk", 12, '男');//kk变量是一个people对象的引用
        kk = null; // kk变量不引用对象, 此时垃圾回收器将回收堆中 new People("kk", 12, '男') 的这个对象
        Runtime.getRuntime().gc();//手动启动垃圾回收器, System.gc()这样也行
    }
}

Run as follows:
Here Insert Picture Description

Released six original articles · won praise 15 · views 1135

Guess you like

Origin blog.csdn.net/qq_45067943/article/details/105232979