Querying swap space in java 9

Selim :

Due to a bug in the sigar library version I am using (returns bogus values for swap), I tried using com.sun.management.OperatingSystemMXBean instead. This worked fine and gave me the desired results (on Windows).

Class<?> sunMxBeanClass = Class.forName("com.sun.management.OperatingSystemMXBean");
sunMxBeanInstance = sunMxBeanClass.cast(ManagementFactory.getOperatingSystemMXBean());
getFreeSwapSpaceSize = getMethodWithName(sunMxBeanClass, "getFreeSwapSpaceSize");
getTotalSwapSpaceSize = getMethodWithName(sunMxBeanClass, "getTotalSwapSpaceSize");

However this breaks with java 9. Is there another way to query swap file / partition information using java? I don't want to introduce a new library or version of sigar.

Cross platform solutions appreciated but windows is enough :--)

Thanks

Holger :

You may try to discover available MX attributes dynamically:

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

There is no dependency to com.sun classes here, not even a reflective access.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=458791&siteId=1
Recommended