简体   繁体   中英

How much memory does my java program use in maximum?

With the following Class which I found here I can get some statistics about the memory of the VM.

But is there also a way to get the maximum of needed memory of my program or a specific method of my program?

/**
* Class: TestMemory
* @author: Viral Patel
* @description: Prints JVM memory utilization statistics
*/
public class TestMemory {

    public static void main(String [] args) {

        int mb = 1024*1024;

        //Getting the runtime reference from system
        Runtime runtime = Runtime.getRuntime();

        System.out.println("##### Heap utilization statistics [MB] #####");

        //Print used memory
        System.out.println("Used Memory:"
            + (runtime.totalMemory() - runtime.freeMemory()) / mb);

        //Print free memory
        System.out.println("Free Memory:"
            + runtime.freeMemory() / mb);

        //Print total available memory
        System.out.println("Total Memory:" + runtime.totalMemory() / mb);

        //Print Maximum available memory
        System.out.println("Max Memory:" + runtime.maxMemory() / mb);
    }
}

So methods themselves don't take up memory on the JVM it is the Objects that you create within the methods etc. Creating the method themselves only creates a bigger footprint on your compiled classes.

You could try profiling with something such as VisualVM or JProfiler . Try setting breakpoints in Debug and watch the memory in these profilers as you step through your program taking note of the so called "problem areas".

These profilers will give you a lot of performance statistics to give you a general idea of the memory needed etc.

Many years ago, I played with Classmexer agent that can measure deep memory usage of a particular object. http://www.javamex.com/tutorials/memory/instrumentation.shtml

IMHO, for the majority of cases, it's more useful to get a big picture usage with Java profiler. I guess, other than for fun, one of hte use case of Classmexer is to do sizing if you really need to store a lot of instances in the heap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM