在Java 9中查询交换空间 [英] Querying swap space in java 9

查看:62
本文介绍了在Java 9中查询交换空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我正在使用的sigar库版本中的错误(返回了虚假的交换值),因此我尝试使用com.sun.management.OperatingSystemMXBean.效果很好,并给了我想要的结果(在Windows上).

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");

但是,这与Java 9冲突.是否还有另一种方法可以使用Java查询交换文件/分区信息? 我不想引入新的库或sigar版本.

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.

赞赏跨平台解决方案,但Windows足够了:-)

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

谢谢

推荐答案

您可以尝试动态发现可用的MX属性:

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());
        }
    }
}

这里没有对com.sun类的依赖,甚至没有反射访问.

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

这篇关于在Java 9中查询交换空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆