简体   繁体   English

我的Java程序最多使用多少内存?

[英]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. 通过在这里找到的以下类,我可以获得有关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. 因此,方法本身不会占用JVM上的内存,这是您在方法等中创建的对象。创建方法本身只会在已编译的类上创建更大的占用空间。

You could try profiling with something such as VisualVM or JProfiler . 您可以尝试使用诸如VisualVMJProfiler之类的配置文件 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". 尝试在Debug中设置断点,并在逐步执行程序时注意所谓的“问题区域”,观察这些事件探查器中的内存。

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. 许多年前,我玩过Classmexer代理,该代理可以测量特定对象的深层内存使用情况。 http://www.javamex.com/tutorials/memory/instrumentation.shtml 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. 恕我直言,在大多数情况下,使用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. 我想,除了好玩之外,如果真的需要在堆中存储很多实例,Classmexer的一个用例之一就是进行大小调整。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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