java - 确定我的应用程序使用了多少内存

标签 java memory ram

我编写了一个java程序,我想看看它运行时使用了多少RAM。有什么方法可以查看与我的程序相关的 RAM 使用量吗?我的意思是像程序的时间使用情况,可以通过在调用主代码之前和之后编写此代码来查看:

long startTime = System.currentTimeMillis();
new Main();
long endTime = System.currentTimeMillis();
System.out.println("Total Time: " + (endTime - startTime));

最佳答案

您可以使用以下类。实现实例化器接口(interface),您可以多次执行同一进程,以获得内存消耗的精确 View

public class SizeOfUtil {

    private static final Runtime runtime = Runtime.getRuntime();
    private static final int OBJECT_COUNT = 100000;

    /**
     * Return the size of an object instantiated using the instantiator
     * 
     * @param instantiator
     * @return byte size of the instantiate object
     */      
    static public int execute(Instantiator instantiator) {
        runGarbageCollection();
        usedMemory();
        Object[] objects = new Object[OBJECT_COUNT + 1];
        long heapSize = 0;
        for (int i = 0; i < OBJECT_COUNT + 1; ++i) {
            Object object = instantiator.execute();
            if (i > 0)
                objects[i] = object;
            else {
                object = null;
                runGarbageCollection();
                heapSize = usedMemory();
            }
        }
        runGarbageCollection();
        long heap2 = usedMemory(); // Take an after heap snapshot:
        final int size = Math.round(((float) (heap2 - heapSize)) / OBJECT_COUNT);

        for (int i = 1; i < OBJECT_COUNT + 1; ++i)
            objects[i] = null;
        objects = null;
        return size;
    }

    private static void runGarbageCollection() {
        for (int r = 0; r < 4; ++r){
            long usedMem1 = usedMemory();
            long usedMem2 = Long.MAX_VALUE;
            for (int i = 0; (usedMem1 < usedMem2) && (i < 500); ++i) {
                runtime.runFinalization();
                runtime.gc();
                Thread.yield();
                usedMem2 = usedMem1;
                usedMem1 = usedMemory();
            }
        }
    }

    private static long usedMemory() {
        return runtime.totalMemory() - runtime.freeMemory();
    }
}

实现接口(interface)

public interface Instantiator { Object execute(); }

使用您要测试的代码

public void sizeOfInteger(){
    int size = SizeOfUtil.execute(new Instantiator(){
        @Override public Object execute() {
            return new Integer (3);
        }
    });
    System.out.println(Integer.class.getSimpleName() + " size = " + size + " bytes");
}

来源:Java Tutorial Java Size of objects

关于java - 确定我的应用程序使用了多少内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15967225/

相关文章:

java - 在 Java 中删除 Arraylist 中的成对元素

java - Jersey REST Web 服务在 Struts 2 中不工作

web - 我应该为 VPS 购买多少内存?

C++ new/new[],它是如何分配内存的?

java - 如何通过Jsoup获取 "select"html元素?

java - Spring RestTemplate 不存在必需的字符串参数

Xcode:为什么我使用presentModalViewcontroller 收到SIGABRT 消息?

ios - 为什么iOS BLE通信时会出现这么多NSNotification,如何释放?

.net - "ContentPresenter.Content"内存泄漏

memory-management - 虚拟内存和物理内存有什么区别?