java - 基础 - GC内存回收
发布时间:2020-12-15 07:31:17 所属栏目:Java 来源:网络整理
导读:? GC内存回收 和 runtime 用来控制内存 ? package gc; public class GCTest { // 垃圾回收测试 GCTest(){ System.out.println( "GCTest被创建了" ); } public void finalize(){ // 重写了回收方法 protected void finalize() throws Throwable { },这个方法
? 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();//让系统回收垃圾,运行后分配的空间可能会减少,因为用不了那么多 long max4 = run.maxMemory(); long total4 = run.totalMemory(); long free4 = run.freeMemory(); System.out.println("max = " + max4 + " total = " + total4 + " free = " + free4); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |