我想用Java监控以下系统信息:
*请注意,我指的是整个系统可用的总内存,而不仅仅是JVM。
我正在寻找一种跨平台的解决方案(Linux、Mac和Windows),它不依赖于我自己的代码调用外部程序或使用JNI。虽然这些都是可行的选择,但如果有人已经有了更好的解决方案,我不希望自己维护特定于操作系统的代码。
如果有一个免费的库可以以一种可靠的、跨平台的方式做到这一点,那就太好了(即使它进行外部调用或使用本机代码本身)。
任何建议都是非常感谢的。
为了清楚起见,我希望获得整个系统的当前CPU使用率,而不仅仅是Java进程。
SIGAR API在一个包中提供了我想要的所有功能,所以它是迄今为止对我的问题的最好回答。然而,由于它是由GPL授权的,我不能将它用于我的原始目的(一个封闭源代码的商业产品)。Hyperic可能会授权SIGAR用于商业用途,但我还没有调查过。对于我的GPL项目,我将来肯定会考虑SIGAR。
对于我目前的需求,我倾向于以下几点:
针对CPU使用率的
OperatingSystemMXBean.getTotalPhysicalMemorySize()
和File.getUsableSpace()
磁盘空间的
OperatingSystemMXBean.getTotalPhysicalMemorySize()
和File.getTotalSpace()
限制:
getSystemLoadAverage()
和磁盘空间查询方法仅在Java6下可用。此外,一些JMX功能可能不适用于所有平台(例如,据报道,getSystemLoadAverage()
在Windows上返回-1 )。
虽然最初是在通用公共许可证下授权的,但它has been changed到了Apache 2.0,这通常可以用于封闭源代码的商业产品。
发布于 2008-09-06 02:23:07
下面的命令可能会让你得到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
}
发布于 2012-10-23 23:36:11
在JDK1.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.
发布于 2014-12-04 05:30:59
这对我来说非常好用,没有任何外部API,只有本机Java隐藏功能:)
import com.sun.management.OperatingSystemMXBean;
...
OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(
OperatingSystemMXBean.class);
// What % CPU load this current JVM is taking, from 0.0-1.0
System.out.println(osBean.getProcessCpuLoad());
// What % load the overall system is at, from 0.0-1.0
System.out.println(osBean.getSystemCpuLoad());
https://stackoverflow.com/questions/47177
复制相似问题