java

GC内存回收 和 runtime 用来控制内存

package gc;

public class GCTest {//垃圾回收测试,对象空间没有任何引用指向它则被视为垃圾
    GCTest(){
        System.out.println("GCTest被创建了");
    }

    public void finalize(){  //重写了回收方法 protected void finalize() throws Throwable { },这个方法会在实例被清除时调用
        System.out.println("GCTest被回收了");
    }



    public static void main(String[] args){

        //runtime
        //内存空间回收管理主要回收的是堆内存,栈内存都是临时变量和方法,生命周期结束后立即回收,方法区内容都是有且只有一份,一直保存不回收
        // 堆内存每次只会分配一部分内存用来使用,够用了会减少,不够用会增加,不会超过最大内存
        //OutOfMemeryError报错就是报的堆内存溢出(一般是因为死循环)

        Runtime run  = Runtime.getRuntime();// 这个class是java自带的,它是单例模式的,可以直接通过class调用(类似于Math)
        long max1 = run.maxMemory();         //获取最大内存(虚拟机分配给的总内存)这个值是不会变的
        long total1 = run.totalMemory();     //获取可用的内存(可以使用的内存),如果当前可以使用的内存不够时会增大。
        long free1 = run.freeMemory();       //获取空闲内存(剩余的空闲内存 = 当前可以使用的内存 - 已使用的内存)
        System.out.println("max = " + max1 + " total = " + total1 + " free = " + free1);


        //gc垃圾回收
        System.out.println("准备创建一个GCTest对象");
        GCTest gc = new GCTest();


        long max2 = run.maxMemory();
        long total2 = run.totalMemory();
        long free2 = run.freeMemory();
        System.out.println("max = " + max2 + " total = " + total2 + " free = " + free2);

        try {
            Thread.sleep(3000); //尝试让这个线程睡眠3秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("准备删除变量gc");
        gc = null;//gc为指向GCTest,gc为null后,没有对象指向上一句创建的对象空间,成为了垃圾。

        long max3 = run.maxMemory();
        long total3 = run.totalMemory();
        long free3 = run.freeMemory();
        System.out.println("max = " + max3 + " tota = " + total3 + " free = " + free3);

        System.out.println("准备清理系统垃圾");
        System.gc();//让系统回收垃圾,运行后分配的空间可能会减少,因为用不了那么多。 gc()是java底层自带的方法。

        long max4 = run.maxMemory();
        long total4 = run.totalMemory();
        long free4 = run.freeMemory();
        System.out.println("max = " + max4 + " total = " + total4 + " free = " + free4);


    }
}

 

 因为我还有其他一些测试其他内容用的class在工程里= =所以垃圾有点多。。。,可以看到运行后分配的内存减少了

原文地址:https://www.cnblogs.com/clamp7724/p/11611610.html