Saikiran Gosikonda
Saikiran Gosikonda

Reputation: 1035

Is there any way to get total RAM memory in use by Java through all JVMs

Is there any standard way to get the size of total memory in use by java?

I found this answer in stackoverflow:
https://stackoverflow.com/a/4335461/5060185

But, the com.sun.* packages are not available in all JVMs.

Upvotes: 3

Views: 1662

Answers (3)

Holger
Holger

Reputation: 298153

Unfortunately, there is no such feature in the standard API. But you can use the extended API in a fail-safe way without explicitly referring to non-standard packages:

public class PhysicalMemory {
    public static void main(String[] args) {
        String[] attr={ "TotalPhysicalMemorySize", "FreePhysicalMemorySize"};
        OperatingSystemMXBean op = ManagementFactory.getOperatingSystemMXBean();
        List<Attribute> al;
        try {
            al = ManagementFactory.getPlatformMBeanServer()
                                  .getAttributes(op.getObjectName(), attr).asList();
        } catch (InstanceNotFoundException | ReflectionException ex) {
            Logger.getLogger(PhysicalMemory.class.getName()).log(Level.SEVERE, null, ex);
            al = Collections.emptyList();
        }
        for(Attribute a: al) {
            System.out.println(a.getName()+": "+a.getValue());
        }
    }
}

This prints the values of the TotalPhysicalMemorySize, FreePhysicalMemorySize attributes, if they are available, regardless of how or in which package they are implemented. This still works in Java 9 where even attempts to access these sun-packages via Reflection are rejected.

On JREs not having these attributes, there is no platform independent way of getting them, but at least, this code doesn’t bail out with linkage errors but allows to proceed without the information.

Upvotes: 3

Kayaman
Kayaman

Reputation: 73558

You could always execute some suitable external program (like free -m) with ProcessBuilder and parse the output from that. There's no mechanism for getting the total amount of RAM, because Java works with the heap its given. It can't allocate memory beyond that, so for Java the heap is the total memory.

Upvotes: 0

anand1st
anand1st

Reputation: 1176

Might the following help?

Runtime runtime = Runtime.getRuntime();
int mb = 1024 * 1024;
log.info("Heap utilization statistics [MB]\nUsed Memory: {}\nFree Memory: {}\nTotal Memory: {}\nMax Memory: {}",
            (runtime.totalMemory() - runtime.freeMemory()) / mb, runtime.freeMemory() / mb,
            runtime.totalMemory() / mb, runtime.maxMemory() / mb);

Upvotes: 1

Related Questions