问题

我想用Java监视以下系统信息:

  • 当前CPU使用率**(百分比)
  • 可用内存*(免费/总计)
  • 可用磁盘空间(空闲/总计)*请注意,我的意思是整个系统可用的总内存,而不仅仅是JVM。

我正在寻找一种不依赖于我自己的代码调用外部程序或使用JNI的跨平台解决方案(Linux,Mac和Windows)。虽然这些是可行的选择,但如果有人已经拥有更好的解决方案,我宁愿不自己维护特定于操作系统的代码。

如果有一个免费的库可以以可靠的跨平台方式实现,那就太棒了(即使它进行外部调用或使用本机代码本身)。

任何建议都非常感谢。

为了澄清,我想获得整个系统的当前CPU使用率,而不仅仅是Java进程。

SIGAR API在一个软件包中提供了我正在寻找的所有功能,因此它是迄今为止我的问题的最佳答案。但是,由于它是根据GPL许可的,我不能将它用于我的原始目的(封闭源,商业产品)。 Hyperic可能会将SIGAR许可用于商业用途,但我没有调查过。对于我的GPL项目,我将来肯定会考虑SIGAR。

根据我目前的需求,我倾向于以下方面:

  • 对于CPU使用情况,OperatingSystemMXBean.getSystemLoadAverage()/ OperatingSystemMXBean.getAvailableProcessors()(每个CPU的平均负载)
  • 对于内存,OperatingSystemMXBean.getTotalPhysicalMemorySize()和OperatingSystemMXBean.getFreePhysicalMemorySize()
  • 对于磁盘空间,File.getTotalSpace()和File.getUsableSpace()

限制:

404642218和磁盘空间查询方法仅在Java 6下可用。此外,某些JMX功能可能并非对所有平台都可用(即,据报道Windows上有getSystemLoadAverage()返回-1)。

虽然最初根据GPL许可,但它通常可用于闭源,商业产品.has been changedApache 2.0


#1 热门回答(58 赞)

顺着我提到的in this post。我建议你使用SIGAR API。我在自己的一个应用程序中使用SIGAR API,这很棒。你会发现它是稳定的,得到很好的支持,并且充满了有用的例子。它是开源的,具有aGPL 2Apache 2.0许可证。一探究竟。我觉得它会满足你的需求。

使用Java和Sigar API,你可以获得内存,CPU,磁盘,负载平均,网络接口信息和指标,进程表信息,路由信息等。


#2 热门回答(44 赞)

以下据称可以获得CPU和RAM。有关更多详细信息,请参见ManagementFactory

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

private static void printUsage() {
  OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
  for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {
    method.setAccessible(true);
    if (method.getName().startsWith("get")
        && Modifier.isPublic(method.getModifiers())) {
            Object value;
        try {
            value = method.invoke(operatingSystemMXBean);
        } catch (Exception e) {
            value = e;
        } // try
        System.out.println(method.getName() + " = " + value);
    } // if
  } // for
}

#3 热门回答(25 赞)

在JDK 1.7中,你可以通过com.sun.management.OperatingSystemMXBean获得系统CPU和内存使用情况。这与java.lang.management.OperatingSystemMXBean不同。

long    getCommittedVirtualMemorySize()
Returns the amount of virtual memory that is guaranteed to be available to the running process in bytes, or -1 if this operation is not supported.

long    getFreePhysicalMemorySize()
Returns the amount of free physical memory in bytes.

long    getFreeSwapSpaceSize()
Returns the amount of free swap space in bytes.

double  getProcessCpuLoad()
Returns the "recent cpu usage" for the Java Virtual Machine process.

long    getProcessCpuTime()
Returns the CPU time used by the process on which the Java virtual machine is running in nanoseconds.

double  getSystemCpuLoad()
Returns the "recent cpu usage" for the whole system.

long    getTotalPhysicalMemorySize()
Returns the total amount of physical memory in bytes.

long    getTotalSwapSpaceSize()
Returns the total amount of swap space in bytes.

原文链接