简体   繁体   中英

How much memory is used by Java program

I've had a look around, and I've seen plenty of answers regarding the question of how much memory is being used by the JVM. These involve things such as calls to Runtime.totalMemory()/Runtime.freeMemory().

However, these don't take into account garbage collection. For example, say we have a large number of objects set to null, which have not yet been garbage collected. Calling Runtime.totalMemory() will show the total memory available as being far below what is actually technically available, as these null objects are still in memory.

So my question is this: is there any better way, be it in Java itself or data from a third party tool that can be ported into the program, to tell dynamically how much memory is being used by a Java program?

EDIT: This needs to be something that can be done in the code itself. Short of calling geObjectSize() on every message sent I can't think of another way of doing it.

您可以像JProfiler这样的探查器,并为特定程序找出实时使用的内存量。

Typically this information is not known prior to garbage collection.

After garbage collection, you can compute the amount of currently used memory with Runtime.totalMemory() and Runtime.freeMemory() , as you note.

... say we have a large number of objects set to null ...

Objects cannot be set to null. You may set references to objects to null. Setting a particular reference to an object to null does not immediately mark the object as eligible for collection .

Objects can be collected when they're no longer reachable . Part of garbage collection is determining whether an object is no longer reachable.

One thing you could try is to suggest to the virtual machine that it free more memory. However, this is just a suggestion, so there might actually be more memory available after subsequent garbage collection.

public long getUpperBoundOfActiveMemoryUsage() {
    System.gc(); // Suggest that some garbage collection occur.

    return getUsedMemory();
}

public long getUsedMemory() {
    Runtime runtime = Runtime.getRuntime();
    long totalMemory = runtime.totalMemory();
    long freeMemory = runtime.freeMemory();
    long usedMemory = totalMemory - freeMemory;
    return usedMemory;
}

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