获取操作系统级别的系统信息

时间:2008-08-25 01:49:55

标签: java memory resources system

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

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

我希望在不使用JNI的情况下获取此信息。

16 个答案:

答案 0 :(得分:196)

您可以从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());
    }
  }
}

答案 1 :(得分:93)

java.lang.management包确实为您提供了比运行时更多的信息 - 例如,它将为您提供与非堆内存(ManagementFactory.getMemoryMXBean().getHeapMemoryUsage())分开的堆内存(ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage())。

您还可以获得进程CPU使用率(无需编写自己的JNI代码),但需要将java.lang.management.OperatingSystemMXBean强制转换为com.sun.management.OperatingSystemMXBean。这适用于Windows和Linux,我还没有在其他地方测试过。

例如......更频繁地调用get getCpuUsage()方法以获得更准确的读数。

public class PerformanceMonitor { 
    private int  availableProcessors = getOperatingSystemMXBean().getAvailableProcessors();
    private long lastSystemTime      = 0;
    private long lastProcessCpuTime  = 0;

    public synchronized double getCpuUsage()
    {
        if ( lastSystemTime == 0 )
        {
            baselineCounters();
            return;
        }

        long systemTime     = System.nanoTime();
        long processCpuTime = 0;

        if ( getOperatingSystemMXBean() instanceof OperatingSystemMXBean )
        {
            processCpuTime = ( (OperatingSystemMXBean) getOperatingSystemMXBean() ).getProcessCpuTime();
        }

        double cpuUsage = (double) ( processCpuTime - lastProcessCpuTime ) / ( systemTime - lastSystemTime );

        lastSystemTime     = systemTime;
        lastProcessCpuTime = processCpuTime;

        return cpuUsage / availableProcessors;
    }

    private void baselineCounters()
    {
        lastSystemTime = System.nanoTime();

        if ( getOperatingSystemMXBean() instanceof OperatingSystemMXBean )
        {
            lastProcessCpuTime = ( (OperatingSystemMXBean) getOperatingSystemMXBean() ).getProcessCpuTime();
        }
    }
}

答案 2 :(得分:40)

我认为最好的方法是实现SIGAR API by Hyperic。它适用于大多数主要操作系统(靠近任何现代设备)并且非常容易使用。开发人员对他们的论坛和邮件列表非常敏感。我也喜欢它是 GPL2 Apache licensed。它们在Java中也提供了大量的例子!

SIGAR == System Information, Gathering And Reporting tool.

答案 3 :(得分:22)

有一个使用JNA的Java项目(因此没有安装本机库)并且正处于活动开发阶段。它目前支持Linux,OSX,Windows,Solaris和FreeBSD,并提供RAM,CPU,电池和文件系统信息。

答案 4 :(得分:11)

您可以使用System.getenv()获取一些系统级信息,并将相关的环境变量名称作为参数传递。例如,在Windows上:

System.getenv("PROCESSOR_IDENTIFIER")
System.getenv("PROCESSOR_ARCHITECTURE")
System.getenv("PROCESSOR_ARCHITEW6432")
System.getenv("NUMBER_OF_PROCESSORS")

对于其他操作系统,相关环境变量的存在/不存在和名称将有所不同。

答案 5 :(得分:11)

对于Windows,我就是这样。

    com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();

    long physicalMemorySize = os.getTotalPhysicalMemorySize();
    long freePhysicalMemory = os.getFreePhysicalMemorySize();
    long freeSwapSize = os.getFreeSwapSpaceSize();
    long commitedVirtualMemorySize = os.getCommittedVirtualMemorySize();

以下是link的详细信息。

答案 6 :(得分:6)

查看java.lang.management包中提供的API。例如:

  • OperatingSystemMXBean.getSystemLoadAverage()
  • ThreadMXBean.getCurrentThreadCpuTime()
  • ThreadMXBean.getCurrentThreadUserTime()

那里还有许多其他有用的东西。

答案 7 :(得分:6)

通过maven添加OSHI依赖:

<dependency>
    <groupId>com.github.dblock</groupId>
    <artifactId>oshi-core</artifactId>
    <version>2.2</version>
</dependency>

获得剩余百分比的电池容量:

SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
for (PowerSource pSource : hal.getPowerSources()) {
    System.out.println(String.format("%n %s @ %.1f%%", pSource.getName(), pSource.getRemainingCapacity() * 100d));
}

答案 8 :(得分:5)

通常,要获得低级操作系统信息,您可以调用操作系统特定的命令,这些命令可以为您提供Runtime.exec()所需的信息,或者在Linux中读取/ proc / *等文件。

答案 9 :(得分:5)

CPU使用率并不简单 - 通过com.sun.management.OperatingSystemMXBean.getProcessCpuTime的java.lang.management接近(请参阅上面Patrick的优秀代码片段)但请注意,它只能访问CPU在您的内容中花费的时间处理。它不会告诉您在其他进程中花费的CPU时间,甚至不会告诉您与您的进程相关的系统活动所花费的CPU时间。

例如,我有一个网络密集型的java进程 - 它是唯一运行的,CPU是99%,但只有55%报告为“处理器CPU”。

甚至没有让我开始“平均负载”,因为它是无用的,尽管它是MX bean上唯一与cpu相关的项目。如果只有太阳在他们偶尔的智慧中暴露出类似“getTotalCpuTime”......

严重的CPU监控Matt提到的SIGAR似乎是最好的选择。

答案 10 :(得分:3)

它仍在开发中,但您已经可以使用jHardware

这是一个使用Java废弃系统数据的简单库。它适用于Linux和Windows。

ProcessorInfo info = HardwareInfo.getProcessorInfo();
//Get named info
System.out.println("Cache size: " + info.getCacheSize());        
System.out.println("Family: " + info.getFamily());
System.out.println("Speed (Mhz): " + info.getMhz());
//[...]

答案 11 :(得分:2)

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

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

答案 12 :(得分:2)

Windows上,您可以运行systeminfo命令并使用以下代码检索其输出:

private static class WindowsSystemInformation
{
    static String get() throws IOException
    {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec("systeminfo");
        BufferedReader systemInformationReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        StringBuilder stringBuilder = new StringBuilder();
        String line;

        while ((line = systemInformationReader.readLine()) != null)
        {
            stringBuilder.append(line);
            stringBuilder.append(System.lineSeparator());
        }

        return stringBuilder.toString().trim();
    }
}

答案 13 :(得分:2)

一种可以用来获取操作系统级别信息的简单方法,我在Mac上进行了测试,效果很好:

 OperatingSystemMXBean osBean =
        (OperatingSystemMXBean)ManagementFactory.getOperatingSystemMXBean();
    return osBean.getProcessCpuLoad();

您可以找到操作系统here的许多相关指标

答案 14 :(得分:1)

嘿,你可以用java / com集成来做到这一点。通过访问WMI功能,您可以获得所有信息。

答案 15 :(得分:0)

要在Java代码中获取1分钟,5分钟和15分钟的系统平均负载,可以通过使用以下命令并对其进行解释来执行命令import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:async'; import 'dart:convert'; class ShowDetails extends StatefulWidget { // var res; // ShowDetails({this.res}); @override _ShowDetailsState createState() => _ShowDetailsState(); } class _ShowDetailsState extends State<ShowDetails> { // var data; // void initState() { // // TODO: implement initState // super.initState(); // data = widget.res['data']; // } @override Widget build(BuildContext context) { return Scaffold( body: new ListView( children: <Widget>[ new Column( children: <Widget>[ new Container( child: new Row( children: <Widget>[ new ListView.builder( shrinkWrap: true, itemBuilder: (BuildContext context, int index) { return new Stack( children: <Widget>[ new Padding( padding: const EdgeInsets.only(left: 50.0), child: new Card( margin: new EdgeInsets.all(20.0), child: new Container( width: double.infinity, height: 200.0, color: Colors.green, ), ), ), new Positioned( top: 0.0, bottom: 0.0, left: 35.0, child: new Container( height: double.infinity, width: 1.0, color: Colors.blue, ), ), new Positioned( top: 100.0, left: 15.0, child: new Container( height: 40.0, width: 40.0, decoration: new BoxDecoration( shape: BoxShape.circle, color: Colors.white, ), child: new Container( margin: new EdgeInsets.all(5.0), height: 30.0, width: 30.0, decoration: new BoxDecoration( shape: BoxShape.circle, color: Colors.red), ), ), ) ], ); }, itemCount: 5, ) ], )), new Container( padding: EdgeInsets.symmetric(vertical: 20.0), child: Column( children: <Widget>[ new Column( children: <Widget>[ new Text("Package Details", style: new TextStyle( fontWeight: FontWeight.w600, color: Color(0xffd01818), fontSize: 25.0, )), new Container( //padding: new EdgeInsets.symmetric(vertical: 0.0), child: new Row( children: <Widget>[ new Expanded( child: new Container( padding: EdgeInsets.symmetric(vertical: 5.0), alignment: Alignment.center, decoration: new BoxDecoration( borderRadius: new BorderRadius.all( Radius.circular(10.0)), color: Color(0xffffe88e), ), child: new Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Text( "Packages Count:", style: new TextStyle( fontWeight: FontWeight.w400, ), ), ], ))), new Expanded( child: new Container( padding: EdgeInsets.symmetric(vertical: 5.0), alignment: Alignment.center, decoration: new BoxDecoration( borderRadius: new BorderRadius.all( Radius.circular(10.0)), color: Color(0xffff25b43), ), child: new Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Text( "istanbul (IST)", style: new TextStyle( fontWeight: FontWeight.w400, ), ), ], ))), ], ), ), new Container( padding: new EdgeInsets.symmetric(vertical: 20.0), child: new Row( children: <Widget>[ new Expanded( child: new Container( padding: EdgeInsets.symmetric(vertical: 5.0), alignment: Alignment.center, decoration: new BoxDecoration( borderRadius: new BorderRadius.all( Radius.circular(10.0)), color: Color(0xffffe88e), ), child: new Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Text( "Payment Method:", style: new TextStyle( fontWeight: FontWeight.w400), ), ], ))), new Expanded( child: new Container( padding: EdgeInsets.symmetric(vertical: 5.0), alignment: Alignment.center, decoration: new BoxDecoration( borderRadius: new BorderRadius.all( Radius.circular(10.0)), color: Color(0xffff25b43), ), child: new Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Text( '2', style: new TextStyle( fontWeight: FontWeight.w400), ), ], ))), ], ), ), new Container( // padding: new EdgeInsets.symmetric(vertical: 20.0), child: new Row( children: <Widget>[ new Expanded( child: new Container( padding: EdgeInsets.symmetric(vertical: 5.0), alignment: Alignment.center, decoration: new BoxDecoration( borderRadius: new BorderRadius.all( Radius.circular(10.0)), color: Color(0xffffe88e), ), child: new Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Text( "Origin:", style: new TextStyle( fontWeight: FontWeight.w400), ), ], ))), new Expanded( child: new Container( padding: EdgeInsets.symmetric(vertical: 5.0), alignment: Alignment.center, decoration: new BoxDecoration( borderRadius: new BorderRadius.all( Radius.circular(10.0)), color: Color(0xffff25b43), ), child: new Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Text( "2", style: new TextStyle( fontWeight: FontWeight.w400), ), ], ))), ], ), ), ], ), ], )), ], ) ], ), ); } } 来做到这一点:

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