run GC and calculate used memory - Java java.lang.management

Java examples for java.lang.management:MemoryMXBean

Description

run GC and calculate used memory

Demo Code


//package com.java2s;

public class Main {
    private static final Runtime rt = Runtime.getRuntime();

    public static void runGC() {

        for (int r = 0; r < 4; ++r) {
            long used1 = usedMemory();
            long used2 = Long.MAX_VALUE;
            for (int i = 0; (used1 < used2) && (i < 500); ++i) {
                rt.runFinalization();/* w  ww .ja va2 s  .c o  m*/
                rt.gc();
                Thread.yield();
                used2 = used1;
                used1 = usedMemory();
            }
        }
    }

    public static long usedMemory() {
        return rt.totalMemory() - rt.freeMemory();
    }
}

Related Tutorials