<p>I'm currently building a Java app that could end up being run on many different platforms, but primarily variants of Solaris, Linux and Windows.</p>

<p>Has anyone been able to successfully extract information such as the current disk space used, CPU utilisation and memory used in the underlying OS? What about just what the Java app itself is consuming?</p>

<p>Preferrably I'd like to get this information without using JNI.</p>

[{'answer_id': 25583, 'author': 'Matt Cummings', 'author_id': 828, 'author_profile': 'https://Stackoverflow.com/users/828', 'pm_score': 5, 'selected': False, 'text': '<p>I think the best method out there is to implement the <a href="https://github.com/hyperic/sigar" rel="nofollow noreferrer">SIGAR API by Hyperic</a>.  It works for most of the major operating systems ( darn near anything modern ) and is very easy to work with.  The developer(s) are very responsive on their forum and mailing lists.  I also like that it is <strike>GPL2</strike> <a href="https://github.com/hyperic/sigar/blob/master/LICENSE" rel="nofollow noreferrer">Apache licensed</a>.  They provide a ton of examples in Java too!</p>\n\n<p><a href="https://github.com/hyperic/sigar" rel="nofollow noreferrer">SIGAR == System Information, Gathering And Reporting tool.</a></p>\n'}, {'answer_id': 25596, 'author': 'William Brendel', 'author_id': 2405, 'author_profile': 'https://Stackoverflow.com/users/2405', 'pm_score': 9, 'selected': True, 'text': '<p>You can get some limited memory information from the Runtime class. It really isn\'t exactly what you are looking for, but I thought I would provide it for the sake of completeness. Here is a small example. Edit: You can also get disk usage information from the java.io.File class. The disk space usage stuff requires Java 1.6 or higher.</p>\n\n<pre><code>public class Main {\n  public static void main(String[] args) {\n    /* Total number of processors or cores available to the JVM */\n    System.out.println("Available processors (cores): " + \n        Runtime.getRuntime().availableProcessors());\n\n    /* Total amount of free memory available to the JVM */\n    System.out.println("Free memory (bytes): " + \n        Runtime.getRuntime().freeMemory());\n\n    /* This will return Long.MAX_VALUE if there is no preset limit */\n    long maxMemory = Runtime.getRuntime().maxMemory();\n    /* Maximum amount of memory the JVM will attempt to use */\n    System.out.println("Maximum memory (bytes): " + \n        (maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory));\n\n    /* Total memory currently available to the JVM */\n    System.out.println("Total memory available to JVM (bytes): " + \n        Runtime.getRuntime().totalMemory());\n\n    /* Get a list of all filesystem roots on this system */\n    File[] roots = File.listRoots();\n\n    /* For each filesystem root, print some info */\n    for (File root : roots) {\n      System.out.println("File system root: " + root.getAbsolutePath());\n      System.out.println("Total space (bytes): " + root.getTotalSpace());\n      System.out.println("Free space (bytes): " + root.getFreeSpace());\n      System.out.println("Usable space (bytes): " + root.getUsableSpace());\n    }\n  }\n}\n</code></pre>\n'}, {'answer_id': 27502, 'author': 'staffan', 'author_id': 988, 'author_profile': 'https://Stackoverflow.com/users/988', 'pm_score': 3, 'selected': False, 'text': '<p>Have a look at the APIs available in the <a href="http://java.sun.com/javase/6/docs/api/java/lang/management/package-summary.html" rel="noreferrer">java.lang.management</a> package. For example: </p>\n\n<ul>\n<li><code>OperatingSystemMXBean.getSystemLoadAverage()</code></li>\n<li><code>ThreadMXBean.getCurrentThreadCpuTime()</code></li>\n<li><code>ThreadMXBean.getCurrentThreadUserTime()</code></li>\n</ul>\n\n<p>There are loads of other useful things in there as well.</p>\n'}, {'answer_id': 61727, 'author': 'Patrick Wilkes', 'author_id': 6370, 'author_profile': 'https://Stackoverflow.com/users/6370', 'pm_score': 7, 'selected': False, 'text': '<p>The <a href="http://java.sun.com/javase/6/docs/api/java/lang/management/package-summary.html" rel="noreferrer">java.lang.management</a> package does give you a whole lot more info than Runtime - for example it will give you heap memory (<code>ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()</code>) separate from non-heap memory (<code>ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage()</code>).</p>\n\n<p>You can also get process CPU usage (without writing your own JNI code), but you need to cast the <code>java.lang.management.OperatingSystemMXBean</code> to a <code>com.sun.management.OperatingSystemMXBean</code>. This works on Windows and Linux, I haven\'t tested it elsewhere.</p>\n\n<p>For example ... call the get getCpuUsage() method more frequently to get more accurate readings.</p>\n\n<pre><code>public class PerformanceMonitor { \n    private int  availableProcessors = getOperatingSystemMXBean().getAvailableProcessors();\n    private long lastSystemTime      = 0;\n    private long lastProcessCpuTime  = 0;\n\n    public synchronized double getCpuUsage()\n    {\n        if ( lastSystemTime == 0 )\n        {\n            baselineCounters();\n            return;\n        }\n\n        long systemTime     = System.nanoTime();\n        long processCpuTime = 0;\n\n        if ( getOperatingSystemMXBean() instanceof OperatingSystemMXBean )\n        {\n            processCpuTime = ( (OperatingSystemMXBean) getOperatingSystemMXBean() ).getProcessCpuTime();\n        }\n\n        double cpuUsage = (double) ( processCpuTime - lastProcessCpuTime ) / ( systemTime - lastSystemTime );\n\n        lastSystemTime     = systemTime;\n        lastProcessCpuTime = processCpuTime;\n\n        return cpuUsage / availableProcessors;\n    }\n\n    private void baselineCounters()\n    {\n        lastSystemTime = System.nanoTime();\n\n        if ( getOperatingSystemMXBean() instanceof OperatingSystemMXBean )\n        {\n            lastProcessCpuTime = ( (OperatingSystemMXBean) getOperatingSystemMXBean() ).getProcessCpuTime();\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 677173, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Hey you can do this with java/com integration.  By accessing WMI features you can get all the information.</p>\n'}, {'answer_id': 678954, 'author': 'Peter Lawrey', 'author_id': 57695, 'author_profile': 'https://Stackoverflow.com/users/57695', 'pm_score': 3, 'selected': False, 'text': '<p>Usually, to get low level OS information you can call OS specific commands which give you the information you want with Runtime.exec() or read files such as /proc/* in Linux.</p>\n'}, {'answer_id': 937635, 'author': 'Partly Cloudy', 'author_id': 109079, 'author_profile': 'https://Stackoverflow.com/users/109079', 'pm_score': 3, 'selected': False, 'text': '<p>CPU usage isn\'t straightforward -- java.lang.management via com.sun.management.OperatingSystemMXBean.getProcessCpuTime comes close (see Patrick\'s excellent code snippet above) but note that it only gives access to time the CPU spent in your process.  it won\'t tell you about CPU time spent in other processes, or even CPU time spent doing system activities related to your process.</p>\n\n<p>for instance i have a network-intensive java process -- it\'s the only thing running and the CPU is at 99% but only 55% of that is reported as "processor CPU".</p>\n\n<p>don\'t even get me started on "load average" as it\'s next to useless, despite being the only cpu-related item on the MX bean.  if only sun in their occasional wisdom exposed something like "getTotalCpuTime"...</p>\n\n<p>for serious CPU monitoring SIGAR mentioned by Matt seems the best bet.</p>\n'}, {'answer_id': 3098296, 'author': 'dB.', 'author_id': 123094, 'author_profile': 'https://Stackoverflow.com/users/123094', 'pm_score': 5, 'selected': False, 'text': '<p>There\'s a Java project that uses JNA (so no native libraries to install) and is in active development. It currently supports Linux, OSX, Windows, Solaris and FreeBSD and provides RAM, CPU, Battery and file system information.</p>\n\n<ul>\n<li><a href="https://github.com/oshi/oshi" rel="noreferrer">https://github.com/oshi/oshi</a></li>\n</ul>\n'}, {'answer_id': 8076368, 'author': 'petro', 'author_id': 1039268, 'author_profile': 'https://Stackoverflow.com/users/1039268', 'pm_score': 2, 'selected': False, 'text': '<p>If you are using Jrockit VM then here is an other way of getting VM CPU usage. Runtime bean can also give you CPU load per processor. I have used this only on Red Hat Linux to observer Tomcat performance. You have to enable JMX remote in catalina.sh for this to work.</p>\n\n<pre><code>JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://my.tomcat.host:8080/jmxrmi");\nJMXConnector jmxc = JMXConnectorFactory.connect(url, null);     \nMBeanServerConnection conn = jmxc.getMBeanServerConnection();       \nObjectName name = new ObjectName("oracle.jrockit.management:type=Runtime");\nDouble jvmCpuLoad =(Double)conn.getAttribute(name, "VMGeneratedCPULoad");\n</code></pre>\n'}, {'answer_id': 11989443, 'author': 'Alexandr', 'author_id': 634281, 'author_profile': 'https://Stackoverflow.com/users/634281', 'pm_score': 4, 'selected': False, 'text': '<p>You can get some system-level information by using <code>System.getenv()</code>, passing the relevant environment variable name as a parameter. For example, on Windows:</p>\n\n<pre><code>System.getenv("PROCESSOR_IDENTIFIER")\nSystem.getenv("PROCESSOR_ARCHITECTURE")\nSystem.getenv("PROCESSOR_ARCHITEW6432")\nSystem.getenv("NUMBER_OF_PROCESSORS")\n</code></pre>\n\n<p>For other operating systems the presence/absence and names of the relevant environment variables will differ.</p>\n'}, {'answer_id': 35758362, 'author': 'profesor_falken', 'author_id': 1774614, 'author_profile': 'https://Stackoverflow.com/users/1774614', 'pm_score': 2, 'selected': False, 'text': '<p>It is still under development but you can already use <a href="https://github.com/profesorfalken/jHardware" rel="nofollow">jHardware</a> </p>\n\n<p>It is a simple library that scraps system data using Java. It works in both Linux and Windows.</p>\n\n<pre><code>ProcessorInfo info = HardwareInfo.getProcessorInfo();\n//Get named info\nSystem.out.println("Cache size: " + info.getCacheSize());        \nSystem.out.println("Family: " + info.getFamily());\nSystem.out.println("Speed (Mhz): " + info.getMhz());\n//[...]\n</code></pre>\n'}, {'answer_id': 36533445, 'author': 'Oleksii Kyslytsyn', 'author_id': 1851286, 'author_profile': 'https://Stackoverflow.com/users/1851286', 'pm_score': 3, 'selected': False, 'text': '<p>Add OSHI dependency via maven:</p>\n\n<pre><code>&lt;dependency&gt;\n    &lt;groupId&gt;com.github.dblock&lt;/groupId&gt;\n    &lt;artifactId&gt;oshi-core&lt;/artifactId&gt;\n    &lt;version&gt;2.2&lt;/version&gt;\n&lt;/dependency&gt;\n</code></pre>\n\n<p>Get a battery capacity left in percentage:</p>\n\n<pre><code>SystemInfo si = new SystemInfo();\nHardwareAbstractionLayer hal = si.getHardware();\nfor (PowerSource pSource : hal.getPowerSources()) {\n    System.out.println(String.format("%n %s @ %.1f%%", pSource.getName(), pSource.getRemainingCapacity() * 100d));\n}\n</code></pre>\n'}, {'answer_id': 38127012, 'author': 'Yan Khonski', 'author_id': 1839360, 'author_profile': 'https://Stackoverflow.com/users/1839360', 'pm_score': 4, 'selected': False, 'text': '<p>For windows I went this way.</p>\n\n<pre><code>    com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();\n\n    long physicalMemorySize = os.getTotalPhysicalMemorySize();\n    long freePhysicalMemory = os.getFreePhysicalMemorySize();\n    long freeSwapSize = os.getFreeSwapSpaceSize();\n    long commitedVirtualMemorySize = os.getCommittedVirtualMemorySize();\n</code></pre>\n\n<p>Here is the <a href="http://www.programcreek.com/java-api-examples/index.php?api=java.lang.management.OperatingSystemMXBean" rel="noreferrer">link</a> with details.</p>\n'}, {'answer_id': 40281599, 'author': 'BullyWiiPlaza', 'author_id': 3764804, 'author_profile': 'https://Stackoverflow.com/users/3764804', 'pm_score': 2, 'selected': False, 'text': '<p>On <code>Windows</code>, you can run the <code>systeminfo</code> command and retrieves its output for instance with the following code:</p>\n\n<pre><code>private static class WindowsSystemInformation\n{\n    static String get() throws IOException\n    {\n        Runtime runtime = Runtime.getRuntime();\n        Process process = runtime.exec("systeminfo");\n        BufferedReader systemInformationReader = new BufferedReader(new InputStreamReader(process.getInputStream()));\n\n        StringBuilder stringBuilder = new StringBuilder();\n        String line;\n\n        while ((line = systemInformationReader.readLine()) != null)\n        {\n            stringBuilder.append(line);\n            stringBuilder.append(System.lineSeparator());\n        }\n\n        return stringBuilder.toString().trim();\n    }\n}\n</code></pre>\n'}, {'answer_id': 55832821, 'author': 'Amandeep Singh', 'author_id': 771226, 'author_profile': 'https://Stackoverflow.com/users/771226', 'pm_score': 2, 'selected': False, 'text': '<p>One simple way which can be used to get the OS level information and I tested in my Mac which works well :</p>\n\n<pre><code> OperatingSystemMXBean osBean =\n        (OperatingSystemMXBean)ManagementFactory.getOperatingSystemMXBean();\n    return osBean.getProcessCpuLoad();\n</code></pre>\n\n<p>You can find many relevant metrics of the operating system <a href="https://zgrepcode.com/examples/java/com/sun/management/operatingsystemmxbean-implementations" rel="nofollow noreferrer">here</a> </p>\n'}, {'answer_id': 59552028, 'author': 'krishna Prasad', 'author_id': 3181159, 'author_profile': 'https://Stackoverflow.com/users/3181159', 'pm_score': 2, 'selected': False, 'text': '<p>To get the <strong>System Load average</strong> of 1 minute, 5 minutes and 15 minutes inside the java code, you can do this by executing the command <code>cat /proc/loadavg</code> using and interpreting it as below:</p>\n\n<pre><code>    Runtime runtime = Runtime.getRuntime();\n\n    BufferedReader br = new BufferedReader(\n        new InputStreamReader(runtime.exec("cat /proc/loadavg").getInputStream()));\n\n    String avgLine = br.readLine();\n    System.out.println(avgLine);\n    List&lt;String&gt; avgLineList = Arrays.asList(avgLine.split("\\\\s+"));\n    System.out.println(avgLineList);\n    System.out.println("Average load 1 minute : " + avgLineList.get(0));\n    System.out.println("Average load 5 minutes : " + avgLineList.get(1));\n    System.out.println("Average load 15 minutes : " + avgLineList.get(2));\n</code></pre>\n\n<p>And to get the <strong>physical system memory</strong> by executing the command <code>free -m</code> and then interpreting it as below:</p>\n\n<pre><code>Runtime runtime = Runtime.getRuntime();\n\nBufferedReader br = new BufferedReader(\n    new InputStreamReader(runtime.exec("free -m").getInputStream()));\n\nString line;\nString memLine = "";\nint index = 0;\nwhile ((line = br.readLine()) != null) {\n  if (index == 1) {\n    memLine = line;\n  }\n  index++;\n}\n//                  total        used        free      shared  buff/cache   available\n//    Mem:          15933        3153        9683         310        3097       12148\n//    Swap:          3814           0        3814\n\nList&lt;String&gt; memInfoList = Arrays.asList(memLine.split("\\\\s+"));\nint totalSystemMemory = Integer.parseInt(memInfoList.get(1));\nint totalSystemUsedMemory = Integer.parseInt(memInfoList.get(2));\nint totalSystemFreeMemory = Integer.parseInt(memInfoList.get(3));\n\nSystem.out.println("Total system memory in mb: " + totalSystemMemory);\nSystem.out.println("Total system used memory in mb: " + totalSystemUsedMemory);\nSystem.out.println("Total system free memory in mb: "   + totalSystemFreeMemory);\n</code></pre>\n'}, {'answer_id': 73582584, 'author': 'Priidu Neemre', 'author_id': 1021943, 'author_profile': 'https://Stackoverflow.com/users/1021943', 'pm_score': 0, 'selected': False, 'text': '<p>Not exactly what you asked for, but I\'d recommend checking out <a href="https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ArchUtils.html" rel="nofollow noreferrer">ArchUtils</a> and <a href="https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/SystemUtils.html" rel="nofollow noreferrer">SystemUtils</a> from <code>commons-lang3</code>. These also contain some relevant helper facilities, <em>e.g.</em>:</p>\n<pre><code>import static org.apache.commons.lang3.ArchUtils.*;\nimport static org.apache.commons.lang3.SystemUtils.*;\n\nSystem.out.printf(&quot;OS architecture: %s\\n&quot;, OS_ARCH); // OS architecture: amd64\nSystem.out.printf(&quot;OS name: %s\\n&quot;, OS_NAME);         // OS name: Linux\nSystem.out.printf(&quot;OS version: %s\\n&quot;, OS_VERSION);   // OS version: 5.18.16-200.fc36.x86_64\n\nSystem.out.printf(&quot;Is Linux? - %b\\n&quot;, IS_OS_LINUX);     // Is Linux? - true\nSystem.out.printf(&quot;Is Mac? - %b\\n&quot;, IS_OS_MAC);         // Is Mac? - false\nSystem.out.printf(&quot;Is Windows? - %b\\n&quot;, IS_OS_WINDOWS); // Is Windows? - false\n\nSystem.out.printf(&quot;JVM name: %s\\n&quot;, JAVA_VM_NAME);       // JVM name: Java HotSpot(TM) 64-Bit Server VM\nSystem.out.printf(&quot;JVM vendor: %s\\n&quot;, JAVA_VM_VENDOR);   // JVM vendor: Oracle Corporation\nSystem.out.printf(&quot;JVM version: %s\\n&quot;, JAVA_VM_VERSION); // JVM version: 11.0.12+8-LTS-237\n\nSystem.out.printf(&quot;Username: %s\\n&quot;, getUserName()); // Username: johndoe\nSystem.out.printf(&quot;Hostname: %s\\n&quot;, getHostName()); // Hostname: garage-pc\n\nvar processor = getProcessor();\nSystem.out.printf(&quot;CPU arch: %s\\n&quot;, processor.getArch())  // CPU arch: BIT_64\nSystem.out.printf(&quot;CPU type: %s\\n&quot;, processor.getType()); // CPU type: X86\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/25552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1693/']