2

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.

Saikiran Gosikonda
  • 928
  • 1
  • 11
  • 29

3 Answers3

3

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.

Holger
  • 285,553
  • 42
  • 434
  • 765
1

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);
anand1st
  • 1,086
  • 10
  • 16
0

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.

Kayaman
  • 72,141
  • 5
  • 83
  • 121