JAVA作业,GC的效果

来源:互联网 发布:热血江湖传进阶数据 编辑:程序博客网 时间:2024/05/18 03:06
package demo;

public class DemoFinal {

    private static Runtime runtime = Runtime.getRuntime();

    private static boolean finalized;

    private int buffer[] = new int[10000];

    protected static long printFreeMemory(String prefix) {
        long freeMemory = runtime.freeMemory();
        System.out.print(prefix);
        System.out.println("The free memory is " + freeMemory);        
        return freeMemory;
    }

    public static void main(String args[]) {
        DemoFinal demoFinal = new DemoFinal();
        printFreeMemory("");                
        demoFinal = null;
        long time = System.currentTimeMillis();
        runtime.gc();        
        while (finalized)    ; //waiting for the finalize executed
        System.out.print("The gc Action costs ");
        System.out.print(System.currentTimeMillis()-time);
        System.out.print(" Milliseconds");
          
    }

    protected void finalize() throws Throwable {
        printFreeMemory("After GC,");
        finalized = true;
    }
}