我目前正在构建一个Java应用程序,它最终可以在许多不同的平台上运行,但主要是Solaris、Linux和Windows的变体。

是否有人能够成功地提取诸如当前使用的磁盘空间、CPU利用率和底层操作系统中使用的内存等信息?Java应用程序本身正在消耗什么呢?

我希望在不使用JNI的情况下获得这些信息。


当前回答

您可以从Runtime类中获得一些有限的内存信息。它确实不是您正在寻找的,但我认为为了完整性起见,我将提供它。这里有一个小例子。编辑:您还可以从java.io.File类获得磁盘使用信息。磁盘空间使用问题需要Java 1.6或更高版本。

public class Main {
  public static void main(String[] args) {
    /* Total number of processors or cores available to the JVM */
    System.out.println("Available processors (cores): " + 
        Runtime.getRuntime().availableProcessors());

    /* Total amount of free memory available to the JVM */
    System.out.println("Free memory (bytes): " + 
        Runtime.getRuntime().freeMemory());

    /* This will return Long.MAX_VALUE if there is no preset limit */
    long maxMemory = Runtime.getRuntime().maxMemory();
    /* Maximum amount of memory the JVM will attempt to use */
    System.out.println("Maximum memory (bytes): " + 
        (maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory));

    /* Total memory currently available to the JVM */
    System.out.println("Total memory available to JVM (bytes): " + 
        Runtime.getRuntime().totalMemory());

    /* Get a list of all filesystem roots on this system */
    File[] roots = File.listRoots();

    /* For each filesystem root, print some info */
    for (File root : roots) {
      System.out.println("File system root: " + root.getAbsolutePath());
      System.out.println("Total space (bytes): " + root.getTotalSpace());
      System.out.println("Free space (bytes): " + root.getFreeSpace());
      System.out.println("Usable space (bytes): " + root.getUsableSpace());
    }
  }
}

其他回答

我认为最好的方法是通过Hyperic实现SIGAR API。它适用于大多数主要的操作系统(几乎所有现代的操作系统),并且非常容易使用。开发者在他们的论坛和邮件列表上的反应非常积极。我还喜欢它是GPL2 Apache授权的。他们也提供了大量的Java示例!

SIGAR ==系统信息,收集和报告工具。

为了在java代码中获得1分钟,5分钟和15分钟的系统负载平均值,你可以通过执行cat /proc/loadavg命令来做到这一点,并如下所示:

    Runtime runtime = Runtime.getRuntime();

    BufferedReader br = new BufferedReader(
        new InputStreamReader(runtime.exec("cat /proc/loadavg").getInputStream()));

    String avgLine = br.readLine();
    System.out.println(avgLine);
    List<String> avgLineList = Arrays.asList(avgLine.split("\\s+"));
    System.out.println(avgLineList);
    System.out.println("Average load 1 minute : " + avgLineList.get(0));
    System.out.println("Average load 5 minutes : " + avgLineList.get(1));
    System.out.println("Average load 15 minutes : " + avgLineList.get(2));

通过执行free -m命令获取物理系统内存,然后解释如下:

Runtime runtime = Runtime.getRuntime();

BufferedReader br = new BufferedReader(
    new InputStreamReader(runtime.exec("free -m").getInputStream()));

String line;
String memLine = "";
int index = 0;
while ((line = br.readLine()) != null) {
  if (index == 1) {
    memLine = line;
  }
  index++;
}
//                  total        used        free      shared  buff/cache   available
//    Mem:          15933        3153        9683         310        3097       12148
//    Swap:          3814           0        3814

List<String> memInfoList = Arrays.asList(memLine.split("\\s+"));
int totalSystemMemory = Integer.parseInt(memInfoList.get(1));
int totalSystemUsedMemory = Integer.parseInt(memInfoList.get(2));
int totalSystemFreeMemory = Integer.parseInt(memInfoList.get(3));

System.out.println("Total system memory in mb: " + totalSystemMemory);
System.out.println("Total system used memory in mb: " + totalSystemUsedMemory);
System.out.println("Total system free memory in mb: "   + totalSystemFreeMemory);

不是你想要的,但是我建议你从common -lang3中查看ArchUtils和SystemUtils。它们还包含一些相关的辅助工具,例如:

import static org.apache.commons.lang3.ArchUtils.*;
import static org.apache.commons.lang3.SystemUtils.*;

System.out.printf("OS architecture: %s\n", OS_ARCH); // OS architecture: amd64
System.out.printf("OS name: %s\n", OS_NAME);         // OS name: Linux
System.out.printf("OS version: %s\n", OS_VERSION);   // OS version: 5.18.16-200.fc36.x86_64

System.out.printf("Is Linux? - %b\n", IS_OS_LINUX);     // Is Linux? - true
System.out.printf("Is Mac? - %b\n", IS_OS_MAC);         // Is Mac? - false
System.out.printf("Is Windows? - %b\n", IS_OS_WINDOWS); // Is Windows? - false

System.out.printf("JVM name: %s\n", JAVA_VM_NAME);       // JVM name: Java HotSpot(TM) 64-Bit Server VM
System.out.printf("JVM vendor: %s\n", JAVA_VM_VENDOR);   // JVM vendor: Oracle Corporation
System.out.printf("JVM version: %s\n", JAVA_VM_VERSION); // JVM version: 11.0.12+8-LTS-237

System.out.printf("Username: %s\n", getUserName()); // Username: johndoe
System.out.printf("Hostname: %s\n", getHostName()); // Hostname: garage-pc

var processor = getProcessor();
System.out.printf("CPU arch: %s\n", processor.getArch())  // CPU arch: BIT_64
System.out.printf("CPU type: %s\n", processor.getType()); // CPU type: X86

有一个使用JNA(因此不需要安装本机库)的Java项目正在积极开发中。它目前支持Linux, OSX, Windows, Solaris和FreeBSD,并提供RAM, CPU,电池和文件系统信息。

https://github.com/oshi/oshi

如果您正在使用Jrockit虚拟机,那么这里有另一种获取虚拟机CPU使用情况的方法。运行时bean还可以提供每个处理器的CPU负载。我只在Red Hat Linux上使用它来观察Tomcat性能。您必须在catalina.sh中启用JMX remote才能使其工作。

JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://my.tomcat.host:8080/jmxrmi");
JMXConnector jmxc = JMXConnectorFactory.connect(url, null);     
MBeanServerConnection conn = jmxc.getMBeanServerConnection();       
ObjectName name = new ObjectName("oracle.jrockit.management:type=Runtime");
Double jvmCpuLoad =(Double)conn.getAttribute(name, "VMGeneratedCPULoad");