<p>I would like to monitor the following system information in Java:</p>

<ul>
<li>Current CPU usage** (percent)</li>
<li>Available memory* (free/total)</li>
<li><p>Available disk space (free/total)</p>

<p>*Note that I mean overall memory available to the whole system, not just the JVM.</p></li>
</ul>

<p>I'm looking for a cross-platform solution (Linux, Mac, and Windows) that doesn't rely on my own code calling external programs or using JNI. Although these are viable options, I would prefer not to maintain OS-specific code myself if someone already has a better solution.</p>

<p>If there's a free library out there that does this in a reliable, cross-platform manner, that would be great (even if it makes external calls or uses native code itself).</p>

<p>Any suggestions are much appreciated.</p>

<p>To clarify, I would like to get the current CPU usage for the whole system, not just the Java process(es).</p>

<p>The SIGAR API provides all the functionality I'm looking for in one package, so it's the best answer to my question so far. However, due it being licensed under the GPL, I cannot use it for my original purpose (a closed source, commercial product). It's possible that Hyperic may license SIGAR for commercial use, but I haven't looked into it. For my GPL projects, I will definitely consider SIGAR in the future.</p>

<p>For my current needs, I'm leaning towards the following:</p>

<ul>
<li>For CPU usage, <code>OperatingSystemMXBean.getSystemLoadAverage() / OperatingSystemMXBean.getAvailableProcessors()</code> (load average per cpu)</li>
<li>For memory, <code>OperatingSystemMXBean.getTotalPhysicalMemorySize()</code> and <code>OperatingSystemMXBean.getFreePhysicalMemorySize()</code></li>
<li>For disk space, <code>File.getTotalSpace()</code> and <code>File.getUsableSpace()</code></li>
</ul>

<p>Limitations:</p>

<p>The <code>getSystemLoadAverage()</code> and disk space querying methods are only available under Java 6. Also, some JMX functionality may not be available to all platforms (i.e. it's been reported that <code>getSystemLoadAverage()</code> returns -1 on Windows).</p>

<p>Although originally licensed under GPL, it <a href="http://forums.hyperic.com/jiveforums/thread.jspa?threadID=11426&amp;tstart=0" rel="noreferrer">has been changed</a> to <a href="http://support.hyperic.com/display/SIGAR/Home#Home-license" rel="noreferrer">Apache 2.0</a>, which can generally be used for closed source, commercial products.</p>

[{'answer_id': 47191, 'author': 'Matt Sheppard', 'author_id': 797, 'author_profile': 'https://Stackoverflow.com/users/797', 'pm_score': 3, 'selected': False, 'text': '<p>For disk space, if you have Java 6, you can use the <a href="http://java.sun.com/javase/6/docs/api/java/io/File.html#getTotalSpace()" rel="noreferrer">getTotalSpace</a> and <a href="http://java.sun.com/javase/6/docs/api/java/io/File.html#getFreeSpace()" rel="noreferrer">getFreeSpace</a> methods on File. If you\'re not on Java 6, I believe you can use <a href="http://commons.apache.org/io/api-release/index.html?org/apache/commons/io/FileSystemUtils.html" rel="noreferrer">Apache Commons IO</a> to get some of the way there.</p>\n\n<p>I don\'t know of any cross platform way to get CPU usage or Memory usage I\'m afraid.</p>\n'}, {'answer_id': 47199, 'author': 'Eugene Yokota', 'author_id': 3827, 'author_profile': 'https://Stackoverflow.com/users/3827', 'pm_score': 6, 'selected': False, 'text': '<p>The following supposedly gets you CPU and RAM. See <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/management/ManagementFactory.html" rel="noreferrer">ManagementFactory</a> for more details.</p>\n\n<pre><code>import java.lang.management.ManagementFactory;\nimport java.lang.management.OperatingSystemMXBean;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\n\nprivate static void printUsage() {\n  OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();\n  for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {\n    method.setAccessible(true);\n    if (method.getName().startsWith("get")\n        &amp;&amp; Modifier.isPublic(method.getModifiers())) {\n            Object value;\n        try {\n            value = method.invoke(operatingSystemMXBean);\n        } catch (Exception e) {\n            value = e;\n        } // try\n        System.out.println(method.getName() + " = " + value);\n    } // if\n  } // for\n}\n</code></pre>\n'}, {'answer_id': 47290, 'author': 'Matt Cummings', 'author_id': 828, 'author_profile': 'https://Stackoverflow.com/users/828', 'pm_score': 7, 'selected': True, 'text': '<p>Along the lines of what I mentioned <a href="https://stackoverflow.com/questions/25552/using-java-to-get-os-level-system-information#25583">in this post</a>. I recommend you use the <a href="https://github.com/hyperic/sigar" rel="noreferrer">SIGAR API</a>.  I use the SIGAR API in one of my own applications and it is great.  You\'ll find it is stable, well supported, and full of useful examples.  It is open-source with a <strike>GPL 2</strike> Apache 2.0 license.  Check it out.  I have a feeling it will meet your needs.</p>\n\n<p>Using Java and the Sigar API you can get Memory, CPU, Disk, Load-Average, Network Interface info and metrics, Process Table information, Route info, etc.</p>\n'}, {'answer_id': 48116, 'author': 'Jason Cohen', 'author_id': 4926, 'author_profile': 'https://Stackoverflow.com/users/4926', 'pm_score': 3, 'selected': False, 'text': '<p>A lot of this is already available via JMX.  With Java 5, JMX is built-in and they include a JMX console viewer with the JDK.</p>\n\n<p>You can use JMX to monitor manually, or invoke JMX commands from Java if you need this information in your own run-time.</p>\n'}, {'answer_id': 835213, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>The following code is Linux (maybe Unix) only, but it works in a real project.</p>\n\n<pre><code>    private double getAverageValueByLinux() throws InterruptedException {\n    try {\n\n        long delay = 50;\n        List&lt;Double&gt; listValues = new ArrayList&lt;Double&gt;();\n        for (int i = 0; i &lt; 100; i++) {\n            long cput1 = getCpuT();\n            Thread.sleep(delay);\n            long cput2 = getCpuT();\n            double cpuproc = (1000d * (cput2 - cput1)) / (double) delay;\n            listValues.add(cpuproc);\n        }\n        listValues.remove(0);\n        listValues.remove(listValues.size() - 1);\n        double sum = 0.0;\n        for (Double double1 : listValues) {\n            sum += double1;\n        }\n        return sum / listValues.size();\n    } catch (Exception e) {\n        e.printStackTrace();\n        return 0;\n    }\n\n}\n\nprivate long getCpuT throws FileNotFoundException, IOException {\n    BufferedReader reader = new BufferedReader(new FileReader("/proc/stat"));\n    String line = reader.readLine();\n    Pattern pattern = Pattern.compile("\\\\D+(\\\\d+)\\\\D+(\\\\d+)\\\\D+(\\\\d+)\\\\D+(\\\\d+)")\n    Matcher m = pattern.matcher(line);\n\n    long cpuUser = 0;\n    long cpuSystem = 0;\n    if (m.find()) {\n        cpuUser = Long.parseLong(m.group(1));\n        cpuSystem = Long.parseLong(m.group(3));\n    }\n    return cpuUser + cpuSystem;\n}\n</code></pre>\n'}, {'answer_id': 2841055, 'author': 'Md. Mukit Hasan', 'author_id': 342030, 'author_profile': 'https://Stackoverflow.com/users/342030', 'pm_score': 2, 'selected': False, 'text': '<p>Make a batch file "Pc.bat" as,\ntypeperf -sc 1 "\\mukit\\processor(_Total)\\%% Processor Time"</p>\n\n<p>You can use the class MProcess,</p>\n\n<p><pre>\n/*\n *Md. Mukit Hasan\n *CSE-JU,35\n **/\nimport java.io.*;</p>\n\n<p>public class MProcessor {</p>\n\n<code>public MProcessor() {\n    String s;\n    try {\n        Process ps = Runtime.getRuntime().exec("Pc.bat");\n        BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));\n        while((s = br.readLine()) != null) {\n            System.out.println(s);\n        }\n    }\n    catch( Exception ex ) {\n        System.out.println(ex.toString());\n    }\n}\n</code></pre>\n\n<p>}\n</p>\n\n<p>Then after some string manipulation, you get the CPU use. You can use the same process for other tasks.</p>\n\n<p>--Mukit Hasan</p>\n'}, {'answer_id': 3095779, 'author': 'ludovicc', 'author_id': 373467, 'author_profile': 'https://Stackoverflow.com/users/373467', 'pm_score': 4, 'selected': False, 'text': '<p>Have a look at this very detailled article:\n<a href="http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking#UsingaSuninternalclasstogetJVMCPUtime" rel="nofollow noreferrer">http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking#UsingaSuninternalclasstogetJVMCPUtime</a></p>\n\n<p>To get the percentage of CPU used, all you need is some simple maths:</p>\n\n<pre><code>MBeanServerConnection mbsc = ManagementFactory.getPlatformMBeanServer();\n\nOperatingSystemMXBean osMBean = ManagementFactory.newPlatformMXBeanProxy(\nmbsc, ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);\n\nlong nanoBefore = System.nanoTime();\nlong cpuBefore = osMBean.getProcessCpuTime();\n\n// Call an expensive task, or sleep if you are monitoring a remote process\n\nlong cpuAfter = osMBean.getProcessCpuTime();\nlong nanoAfter = System.nanoTime();\n\nlong percent;\nif (nanoAfter &gt; nanoBefore)\n percent = ((cpuAfter-cpuBefore)*100L)/\n   (nanoAfter-nanoBefore);\nelse percent = 0;\n\nSystem.out.println("Cpu usage: "+percent+"%");\n</code></pre>\n\n<p>Note: You must import <code>com.sun.management.OperatingSystemMXBean</code> and not <code>java.lang.management.OperatingSystemMXBean</code>.</p>\n'}, {'answer_id': 13034111, 'author': 'Gp2you', 'author_id': 1659061, 'author_profile': 'https://Stackoverflow.com/users/1659061', 'pm_score': 6, 'selected': False, 'text': '<p>In JDK 1.7, you can get system CPU and memory usage via <a href="http://docs.oracle.com/javase/7/docs/jre/api/management/extension/com/sun/management/OperatingSystemMXBean.html" rel="noreferrer"><code>com.sun.management.OperatingSystemMXBean</code></a>.  This is different than <code>java.lang.management.OperatingSystemMXBean</code>.</p>\n<pre><code>long getCommittedVirtualMemorySize()\n// 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.\n\nlong getFreePhysicalMemorySize()\n// Returns the amount of free physical memory in bytes.\n\nlong getFreeSwapSpaceSize()\n// Returns the amount of free swap space in bytes.\n\ndouble getProcessCpuLoad()\n// Returns the &quot;recent cpu usage&quot; for the Java Virtual Machine process.\n\nlong getProcessCpuTime()\n// Returns the CPU time used by the process on which the Java virtual machine is running in nanoseconds.\n\ndouble getSystemCpuLoad()\n// Returns the &quot;recent cpu usage&quot; for the whole system.\n\nlong getTotalPhysicalMemorySize()\n// Returns the total amount of physical memory in bytes.\n\nlong getTotalSwapSpaceSize()\n// Returns the total amount of swap space in bytes.\n</code></pre>\n'}, {'answer_id': 21772609, 'author': 'pragati', 'author_id': 3309149, 'author_profile': 'https://Stackoverflow.com/users/3309149', 'pm_score': 3, 'selected': False, 'text': '<pre><code>/* YOU CAN TRY THIS TOO */\n\nimport java.io.File;\n import java.lang.management.ManagementFactory;\n// import java.lang.management.OperatingSystemMXBean;\n import java.lang.reflect.Method;\n import java.lang.reflect.Modifier;\n import java.lang.management.RuntimeMXBean;\n import java.io.*;\n import java.net.*;\n import java.util.*;\n import java.io.LineNumberReader;\n import java.lang.management.ManagementFactory;\nimport com.sun.management.OperatingSystemMXBean;\nimport java.lang.management.ManagementFactory;\nimport java.util.Random;\n\n\n\n public class Pragati\n {\n\n     public static void printUsage(Runtime runtime)\n     {\n     long total, free, used;\n     int mb = 1024*1024;\n\n     total = runtime.totalMemory();\n     free = runtime.freeMemory();\n     used = total - free;\n     System.out.println("\\nTotal Memory: " + total / mb + "MB");\n     System.out.println(" Memory Used: " + used / mb + "MB");\n     System.out.println(" Memory Free: " + free / mb + "MB");\n     System.out.println("Percent Used: " + ((double)used/(double)total)*100 + "%");\n     System.out.println("Percent Free: " + ((double)free/(double)total)*100 + "%");\n    }\n    public static void log(Object message)\n         {\n            System.out.println(message);\n         }\n\n        public static int calcCPU(long cpuStartTime, long elapsedStartTime, int cpuCount)\n        {\n             long end = System.nanoTime();\n             long totalAvailCPUTime = cpuCount * (end-elapsedStartTime);\n             long totalUsedCPUTime = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime()-cpuStartTime;\n             //log("Total CPU Time:" + totalUsedCPUTime + " ns.");\n             //log("Total Avail CPU Time:" + totalAvailCPUTime + " ns.");\n             float per = ((float)totalUsedCPUTime*100)/(float)totalAvailCPUTime;\n             log( per);\n             return (int)per;\n        }\n\n        static boolean isPrime(int n)\n        {\n     // 2 is the smallest prime\n            if (n &lt;= 2)\n            {\n                return n == 2;\n            }\n     // even numbers other than 2 are not prime\n            if (n % 2 == 0)\n            {\n                return false;\n            }\n     // check odd divisors from 3\n     // to the square root of n\n         for (int i = 3, end = (int)Math.sqrt(n); i &lt;= end; i += 2)\n         {\n            if (n % i == 0)\n         {\n         return false;\n        }\n        }\n return true;\n}\n    public static void main(String [] args)\n    {\n            int mb = 1024*1024;\n            int gb = 1024*1024*1024;\n             /* PHYSICAL MEMORY USAGE */\n             System.out.println("\\n**** Sizes in Mega Bytes ****\\n");\n            com.sun.management.OperatingSystemMXBean operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean)ManagementFactory.getOperatingSystemMXBean();\n            //RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();\n            //operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();\n            com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean)\n            java.lang.management.ManagementFactory.getOperatingSystemMXBean();\n            long physicalMemorySize = os.getTotalPhysicalMemorySize();\n            System.out.println("PHYSICAL MEMORY DETAILS \\n");\n            System.out.println("total physical memory : " + physicalMemorySize / mb + "MB ");\n            long physicalfreeMemorySize = os.getFreePhysicalMemorySize();\n            System.out.println("total free physical memory : " + physicalfreeMemorySize / mb + "MB");\n            /* DISC SPACE DETAILS */\n            File diskPartition = new File("C:");\n            File diskPartition1 = new File("D:");\n            File diskPartition2 = new File("E:");\n            long totalCapacity = diskPartition.getTotalSpace() / gb;\n            long totalCapacity1 = diskPartition1.getTotalSpace() / gb;\n            double freePartitionSpace = diskPartition.getFreeSpace() / gb;\n            double freePartitionSpace1 = diskPartition1.getFreeSpace() / gb;\n            double freePartitionSpace2 = diskPartition2.getFreeSpace() / gb;\n            double usablePatitionSpace = diskPartition.getUsableSpace() / gb;\n            System.out.println("\\n**** Sizes in Giga Bytes ****\\n");\n            System.out.println("DISC SPACE DETAILS \\n");\n            //System.out.println("Total C partition size : " + totalCapacity + "GB");\n            //System.out.println("Usable Space : " + usablePatitionSpace + "GB");\n            System.out.println("Free Space in drive C: : " + freePartitionSpace + "GB");\n            System.out.println("Free Space in drive D:  : " + freePartitionSpace1 + "GB");\n            System.out.println("Free Space in drive E: " + freePartitionSpace2 + "GB");\n            if(freePartitionSpace &lt;= totalCapacity%10 || freePartitionSpace1 &lt;= totalCapacity1%10)\n            {\n                System.out.println(" !!!alert!!!!");\n            }\n            else\n                System.out.println("no alert");\n\n            Runtime runtime;\n            byte[] bytes;\n            System.out.println("\\n \\n**MEMORY DETAILS  ** \\n");\n            // Print initial memory usage.\n            runtime = Runtime.getRuntime();\n            printUsage(runtime);\n\n            // Allocate a 1 Megabyte and print memory usage\n            bytes = new byte[1024*1024];\n            printUsage(runtime);\n\n            bytes = null;\n            // Invoke garbage collector to reclaim the allocated memory.\n            runtime.gc();\n\n            // Wait 5 seconds to give garbage collector a chance to run\n            try {\n            Thread.sleep(5000);\n            } catch(InterruptedException e) {\n            e.printStackTrace();\n            return;\n            }\n\n            // Total memory will probably be the same as the second printUsage call,\n            // but the free memory should be about 1 Megabyte larger if garbage\n            // collection kicked in.\n            printUsage(runtime);\n            for(int i = 0; i &lt; 30; i++)\n                     {\n                         long start = System.nanoTime();\n                        // log(start);\n                        //number of available processors;\n                         int cpuCount = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();\n                         Random random = new Random(start);\n                         int seed = Math.abs(random.nextInt());\n                         log("\\n \\n CPU USAGE DETAILS \\n\\n");\n                         log("Starting Test with " + cpuCount + " CPUs and random number:" + seed);\n                         int primes = 10000;\n                         //\n                         long startCPUTime = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();\n                         start = System.nanoTime();\n                         while(primes != 0)\n                         {\n                            if(isPrime(seed))\n                            {\n                                primes--;\n                            }\n                            seed++;\n\n                        }\n                         float cpuPercent = calcCPU(startCPUTime, start, cpuCount);\n                         log("CPU USAGE : " + cpuPercent + " % ");\n\n\n                         try\n                         {\n                             Thread.sleep(1000);\n                         }\n                         catch (InterruptedException e) {}\n        }\n\n            try\n            {\n                Thread.sleep(500);\n            }`enter code here`\n            catch (Exception ignored) { }\n        }\n    }\n</code></pre>\n'}, {'answer_id': 27282046, 'author': 'bizzr3', 'author_id': 1020474, 'author_profile': 'https://Stackoverflow.com/users/1020474', 'pm_score': 5, 'selected': False, 'text': '<p>This works for me perfectly without any external API, just native Java hidden feature :)</p>\n\n<pre><code>import com.sun.management.OperatingSystemMXBean;\n...\nOperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(\n                OperatingSystemMXBean.class);\n// What % CPU load this current JVM is taking, from 0.0-1.0\nSystem.out.println(osBean.getProcessCpuLoad());\n\n// What % load the overall system is at, from 0.0-1.0\nSystem.out.println(osBean.getSystemCpuLoad());\n</code></pre>\n'}, {'answer_id': 56143016, 'author': 'OhadR', 'author_id': 421642, 'author_profile': 'https://Stackoverflow.com/users/421642', 'pm_score': 4, 'selected': False, 'text': '<p>The accepted answer in 2008 recommended SIGAR. However, as a comment from 2014 (@Alvaro) says:</p>\n\n<blockquote>\n  <p>Be careful when using Sigar, there are problems on x64 machines...\n  <a href="https://stackoverflow.com/questions/23405832/sigar-1-6-4-is-crashing-exception-access-violation">Sigar 1.6.4 is crashing: EXCEPTION_ACCESS_VIOLATION</a> and it seems the library\n  doesn\'t get updated since 2010</p>\n</blockquote>\n\n<p>My recommendation is to use <a href="https://github.com/oshi/oshi" rel="noreferrer">https://github.com/oshi/oshi</a></p>\n\n<p>Or the <a href="https://stackoverflow.com/a/27282046/421642">answer mentioned above</a>.</p>\n'}, {'answer_id': 68758496, 'author': 'Coderman69', 'author_id': 14999071, 'author_profile': 'https://Stackoverflow.com/users/14999071', 'pm_score': 0, 'selected': False, 'text': '<pre><code>    OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);\n    System.out.println((osBean.getCpuLoad() * 100) + &quot;%&quot;);\n</code></pre>\n<p>import <code>com.sun.management.OperatingSystemMXBean</code></p>\n<p>It only starts working after the second call so save the osBean and put it in a loop</p>\n'}]
['https://Stackoverflow.com/questions/47177', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2783/']