Get full system memory and system components in java

Asked

Viewed 51 times

-1

Is there any simple or reliable method to take the total memory of the computer and/or the components or models of the computer components?

I did a lot of research and the only thing I found was some articles talking about the class com.sun.management.OperatingSystemMXBean but it is "protected" and this generates an error in Ides and I do not know if it is safe to ignore this error, the end of the day if it is giving some error is because something is wrong.

  • Tried to use java.lang.Runtime? https://stackoverflow.com/a/12807848

  • Runtime returns the information of the current "program", I can not explain well but it does not return the memory of the computer.

1 answer

1


After giving a study I managed to develop a method that does not generate errors and works perfectly using Reflection and the class OperatingSystemMXBean of java.lang

private long getFreeMemoryComputer() {
    try {
        OperatingSystemMXBean system = ManagementFactory.getOperatingSystemMXBean();
        Method getFreeMemory = system.getClass().getMethod("getFreePhysicalMemorySize");
        getFreeMemory.setAccessible(true);
        return (long) getFreeMemory.invoke(system);
    } catch (Exception e) {
        return -1;
    }
}

private long getTotalMemoryComputer() {
    try {
        OperatingSystemMXBean system = ManagementFactory.getOperatingSystemMXBean();
        Method getTotalMemory = system.getClass().getMethod("getTotalPhysicalMemorySize");
        getTotalMemory.setAccessible(true);
        return (long) getTotalMemory.invoke(system);
    } catch (Exception e) {
        return -1;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.