Querying swap space in java 9

好久不见. 提交于 2021-02-07 12:54:40

问题


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


回答1:


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.




回答2:


The jdk.management module exports the com.sun.management API and it works the same way in JDK 9 as it did in JDK 8. So either of the following should work:

com.sun.management.OperatingSystemMXBean mbean
    = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
long free = mbean.getFreePhysicalMemorySize();
long swap = mbean.getTotalSwapSpaceSize();

or

OperatingSystemMXBean mbean = ManagementFactory.getOperatingSystemMXBean();
Class<?> klass = Class.forName("com.sun.management.OperatingSystemMXBean");
Method freeSpaceMethod = klass.getMethod("getFreeSwapSpaceSize");
Method totalSpaceMethod = klass.getMethod("getTotalSwapSpaceSize");
long free = (long) freeSpaceMethod.invoke(mbean);
long swap = (long) totalSpaceMethod.invoke(mbean);


来源:https://stackoverflow.com/questions/48325706/querying-swap-space-in-java-9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!