<p>I need to check CPU and memory usage for the server in java, anyone know how it could be done?</p>

[{'answer_id': 74720, 'author': 'Tim Howland', 'author_id': 4276, 'author_profile': 'https://Stackoverflow.com/users/4276', 'pm_score': 1, 'selected': False, 'text': '<p>If you are using Tomcat, check out <a href="https://code.google.com/p/psi-probe/" rel="nofollow noreferrer">Psi Probe</a>, which lets you monitor internal and external memory consumption as well as a host of other areas.</p>\n'}, {'answer_id': 74724, 'author': 'moonshadow', 'author_id': 11834, 'author_profile': 'https://Stackoverflow.com/users/11834', 'pm_score': 2, 'selected': False, 'text': '<p>Java\'s <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html" rel="nofollow noreferrer">Runtime</a> object can report the JVM\'s memory usage. For CPU consumption you\'ll have to use an external utility, like Unix\'s top or Windows Process Manager.</p>\n'}, {'answer_id': 74742, 'author': 'Rich Adams', 'author_id': 10018, 'author_profile': 'https://Stackoverflow.com/users/10018', 'pm_score': 3, 'selected': False, 'text': "<p>For memory usage, the following will work,</p>\n\n<pre><code>long total = Runtime.getRuntime().totalMemory();\nlong used  = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();\n</code></pre>\n\n<p>For CPU usage, you'll need to use an external application to measure it.</p>\n"}, {'answer_id': 74753, 'author': 'blahspam', 'author_id': 8290, 'author_profile': 'https://Stackoverflow.com/users/8290', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://java.sun.com/developer/technicalArticles/J2SE/jconsole.html" rel="nofollow noreferrer">JConsole</a> is an easy way to monitor a running Java application or you can use a Profiler to get more detailed information on your application. I like using the <a href="http://profiler.netbeans.org/" rel="nofollow noreferrer">NetBeans Profiler</a> for this.</p>\n'}, {'answer_id': 74759, 'author': 'Bill K', 'author_id': 12943, 'author_profile': 'https://Stackoverflow.com/users/12943', 'pm_score': 2, 'selected': False, 'text': '<p>If you use the runtime/totalMemory solution that has been posted in many answers here (I\'ve done that a lot), be sure to force two garbage collections first if you want fairly accurate/consistent results.</p>\n\n<p>For effiency Java usually allows garbage to fill up all of memory before forcing a GC, and even then it\'s not usually a complete GC, so your results for runtime.freeMemory() always be somewhere between the "real" amount of free memory and 0.</p>\n\n<p>The first GC doesn\'t get everything, it gets most of it.</p>\n\n<p>The upswing is that if you just do the freeMemory() call you will get a number that is absolutely useless and varies widely, but if do 2 gc\'s first it is a very reliable gauge.  It also makes the routine MUCH slower (seconds, possibly).</p>\n'}, {'answer_id': 74763, 'author': 'Jeremy', 'author_id': 4419, 'author_profile': 'https://Stackoverflow.com/users/4419', 'pm_score': 6, 'selected': False, 'text': '<p>If you are looking specifically for memory in JVM:</p>\n\n<pre><code>Runtime runtime = Runtime.getRuntime();\n\nNumberFormat format = NumberFormat.getInstance();\n\nStringBuilder sb = new StringBuilder();\nlong maxMemory = runtime.maxMemory();\nlong allocatedMemory = runtime.totalMemory();\nlong freeMemory = runtime.freeMemory();\n\nsb.append("free memory: " + format.format(freeMemory / 1024) + "&lt;br/&gt;");\nsb.append("allocated memory: " + format.format(allocatedMemory / 1024) + "&lt;br/&gt;");\nsb.append("max memory: " + format.format(maxMemory / 1024) + "&lt;br/&gt;");\nsb.append("total free memory: " + format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024) + "&lt;br/&gt;");\n</code></pre>\n\n<p>However, these should be taken only as an estimate...</p>\n'}, {'answer_id': 74801, 'author': 'Telcontar', 'author_id': 518, 'author_profile': 'https://Stackoverflow.com/users/518', 'pm_score': 3, 'selected': False, 'text': '<p>Since Java 1.5 the JDK comes with a new tool: <a href="http://java.sun.com/developer/technicalArticles/J2SE/jconsole.html" rel="noreferrer">JConsole</a> wich can show you the CPU and memory usage of any 1.5 or later JVM. It can do charts of these parameters, export to CSV, show the number of classes loaded, the number of instances, deadlocks, threads etc...</p>\n'}, {'answer_id': 75051, 'author': 'Gregg', 'author_id': 7994, 'author_profile': 'https://Stackoverflow.com/users/7994', 'pm_score': 1, 'selected': False, 'text': '<p>The <a href="http://www.yourkit.com/" rel="nofollow noreferrer">YourKit</a> Java profiler is an excellent commercial solution. You can find further information in the docs on <a href="http://www.yourkit.com/docs/75/help/cpu_profiling/cpu_intro.jsp" rel="nofollow noreferrer">CPU profiling</a> and <a href="http://www.yourkit.com/docs/75/help/memory_profiling/memory_telemetry.jsp" rel="nofollow noreferrer">memory profiling</a>.</p>\n'}, {'answer_id': 75129, 'author': 'Javamann', 'author_id': 10166, 'author_profile': 'https://Stackoverflow.com/users/10166', 'pm_score': 4, 'selected': False, 'text': '<p>JMX, The MXBeans (ThreadMXBean, etc) provided will give you Memory and CPU usages.</p>\n\n<pre><code>OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();\noperatingSystemMXBean.getSystemCpuLoad();\n</code></pre>\n'}, {'answer_id': 76113, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>If you are using the Sun JVM, and are interested in the internal memory usage of the application (how much out of the allocated memory your app is using) I prefer to turn on the JVMs built-in garbage collection logging. You simply add -verbose:gc to the startup command.</p>\n\n<p>From the Sun documentation:</p>\n\n<blockquote>\n  <p>The command line argument -verbose:gc prints information at every\n  collection. Note that the format of the -verbose:gc output is subject\n  to change between releases of the J2SE platform. For example, here is\n  output from a large server application:</p>\n\n<pre><code>[GC 325407K-&gt;83000K(776768K), 0.2300771 secs]\n[GC 325816K-&gt;83372K(776768K), 0.2454258 secs]\n[Full GC 267628K-&gt;83769K(776768K), 1.8479984 secs]\n</code></pre>\n  \n  <p>Here we see two minor collections and one major one. The numbers\n  before and after the arrow</p>\n\n<pre><code>325407K-&gt;83000K (in the first line)\n</code></pre>\n  \n  <p>indicate the combined size of live objects before and after garbage\n  collection, respectively. After minor collections the count includes\n  objects that aren\'t necessarily alive but can\'t be reclaimed, either\n  because they are directly alive, or because they are within or\n  referenced from the tenured generation. The number in parenthesis</p>\n\n<pre><code>(776768K) (in the first line)\n</code></pre>\n  \n  <p>is the total available space, not counting the space in the permanent\n  generation, which is the total heap minus one of the survivor spaces.\n  The minor collection took about a quarter of a second.</p>\n\n<pre><code>0.2300771 secs (in the first line)\n</code></pre>\n</blockquote>\n\n<p>For more info see: <a href="http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html" rel="noreferrer">http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html</a></p>\n'}, {'answer_id': 7870722, 'author': 'Phil', 'author_id': 661773, 'author_profile': 'https://Stackoverflow.com/users/661773', 'pm_score': 2, 'selected': False, 'text': '<p>Here is some simple code to calculate the current memory usage in megabytes:</p>\n\n<pre><code>double currentMemory = ( (double)((double)(Runtime.getRuntime().totalMemory()/1024)/1024))- ((double)((double)(Runtime.getRuntime().freeMemory()/1024)/1024));\n</code></pre>\n'}, {'answer_id': 8038928, 'author': 'Fuangwith S.', 'author_id': 24550, 'author_profile': 'https://Stackoverflow.com/users/24550', 'pm_score': 0, 'selected': False, 'text': '<p>For Eclipse, you can use TPTP (Test and Performance Tools Platform) for analyse memory usage and etc. <a href="http://eclipse.org/articles/Article-TPTP-Profiling-Tool/tptpProfilingArticle.html" rel="nofollow">more information</a></p>\n'}, {'answer_id': 8973770, 'author': 'Dave', 'author_id': 1165214, 'author_profile': 'https://Stackoverflow.com/users/1165214', 'pm_score': 5, 'selected': False, 'text': '<pre><code>import java.io.File;\nimport java.text.NumberFormat;\n\npublic class SystemInfo {\n\n    private Runtime runtime = Runtime.getRuntime();\n\n    public String info() {\n        StringBuilder sb = new StringBuilder();\n        sb.append(this.osInfo());\n        sb.append(this.memInfo());\n        sb.append(this.diskInfo());\n        return sb.toString();\n    }\n\n    public String osName() {\n        return System.getProperty(&quot;os.name&quot;);\n    }\n\n    public String osVersion() {\n        return System.getProperty(&quot;os.version&quot;);\n    }\n\n    public String osArch() {\n        return System.getProperty(&quot;os.arch&quot;);\n    }\n\n    public long totalMem() {\n        return Runtime.getRuntime().totalMemory();\n    }\n\n    public long usedMem() {\n        return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();\n    }\n\n    public String memInfo() {\n        NumberFormat format = NumberFormat.getInstance();\n        StringBuilder sb = new StringBuilder();\n        long maxMemory = runtime.maxMemory();\n        long allocatedMemory = runtime.totalMemory();\n        long freeMemory = runtime.freeMemory();\n        sb.append(&quot;Free memory: &quot;);\n        sb.append(format.format(freeMemory / 1024));\n        sb.append(&quot;&lt;br/&gt;&quot;);\n        sb.append(&quot;Allocated memory: &quot;);\n        sb.append(format.format(allocatedMemory / 1024));\n        sb.append(&quot;&lt;br/&gt;&quot;);\n        sb.append(&quot;Max memory: &quot;);\n        sb.append(format.format(maxMemory / 1024));\n        sb.append(&quot;&lt;br/&gt;&quot;);\n        sb.append(&quot;Total free memory: &quot;);\n        sb.append(format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024));\n        sb.append(&quot;&lt;br/&gt;&quot;);\n        return sb.toString();\n\n    }\n\n    public String osInfo() {\n        StringBuilder sb = new StringBuilder();\n        sb.append(&quot;OS: &quot;);\n        sb.append(this.osName());\n        sb.append(&quot;&lt;br/&gt;&quot;);\n        sb.append(&quot;Version: &quot;);\n        sb.append(this.osVersion());\n        sb.append(&quot;&lt;br/&gt;&quot;);\n        sb.append(&quot;: &quot;);\n        sb.append(this.osArch());\n        sb.append(&quot;&lt;br/&gt;&quot;);\n        sb.append(&quot;Available processors (cores): &quot;);\n        sb.append(runtime.availableProcessors());\n        sb.append(&quot;&lt;br/&gt;&quot;);\n        return sb.toString();\n    }\n\n    public String diskInfo() {\n        /* Get a list of all filesystem roots on this system */\n        File[] roots = File.listRoots();\n        StringBuilder sb = new StringBuilder();\n\n        /* For each filesystem root, print some info */\n        for (File root : roots) {\n            sb.append(&quot;File system root: &quot;);\n            sb.append(root.getAbsolutePath());\n            sb.append(&quot;&lt;br/&gt;&quot;);\n            sb.append(&quot;Total space (bytes): &quot;);\n            sb.append(root.getTotalSpace());\n            sb.append(&quot;&lt;br/&gt;&quot;);\n            sb.append(&quot;Free space (bytes): &quot;);\n            sb.append(root.getFreeSpace());\n            sb.append(&quot;&lt;br/&gt;&quot;);\n            sb.append(&quot;Usable space (bytes): &quot;);\n            sb.append(root.getUsableSpace());\n            sb.append(&quot;&lt;br/&gt;&quot;);\n        }\n        return sb.toString();\n    }\n}\n</code></pre>\n'}, {'answer_id': 15733233, 'author': 'danieln', 'author_id': 1083423, 'author_profile': 'https://Stackoverflow.com/users/1083423', 'pm_score': 4, 'selected': False, 'text': '<p>From <a href="http://knight76.blogspot.co.il/2009/05/how-to-get-java-cpu-usage-jvm-instance.html">here</a></p>\n\n<pre><code>    OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();\n    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();\n    int availableProcessors = operatingSystemMXBean.getAvailableProcessors();\n    long prevUpTime = runtimeMXBean.getUptime();\n    long prevProcessCpuTime = operatingSystemMXBean.getProcessCpuTime();\n    double cpuUsage;\n    try\n    {\n        Thread.sleep(500);\n    }\n    catch (Exception ignored) { }\n\n    operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();\n    long upTime = runtimeMXBean.getUptime();\n    long processCpuTime = operatingSystemMXBean.getProcessCpuTime();\n    long elapsedCpu = processCpuTime - prevProcessCpuTime;\n    long elapsedTime = upTime - prevUpTime;\n\n    cpuUsage = Math.min(99F, elapsedCpu / (elapsedTime * 10000F * availableProcessors));\n    System.out.println("Java CPU: " + cpuUsage);\n</code></pre>\n'}, {'answer_id': 31187628, 'author': 'sbeliakov', 'author_id': 2182091, 'author_profile': 'https://Stackoverflow.com/users/2182091', 'pm_score': 2, 'selected': False, 'text': '<p>I would also add the following way to track CPU Load:</p>\n\n<pre><code>import java.lang.management.ManagementFactory;\nimport com.sun.management.OperatingSystemMXBean;\n\ndouble getCpuLoad() {\n    OperatingSystemMXBean osBean =\n        (com.sun.management.OperatingSystemMXBean) ManagementFactory.\n        getPlatformMXBeans(OperatingSystemMXBean.class);\n    return osBean.getProcessCpuLoad();\n}\n</code></pre>\n\n<p>You can read more <a href="https://www.java.net/community-item/hidden-java-7-features-%E2%80%93-system-and-process-cpu-load-monitoring" rel="nofollow">here</a></p>\n'}, {'answer_id': 69076398, 'author': 'Antonio Noack', 'author_id': 4979303, 'author_profile': 'https://Stackoverflow.com/users/4979303', 'pm_score': 0, 'selected': False, 'text': '<p>I want to add a note to the existing answers:</p>\n<p>These methods only keep track of JVM Memory. The actual process may consume more memory.</p>\n<p>java.nio.ByteBuffer.allocateDirect() is a function/library, that is easily missed, and indeed allocated native memory, that is not part of the Java memory management.</p>\n<p>On Linux, you may use something like this to get the actually consumed memory: <a href="https://linuxhint.com/check_memory_usage_process_linux/" rel="nofollow noreferrer">https://linuxhint.com/check_memory_usage_process_linux/</a></p>\n'}]
['https://Stackoverflow.com/questions/74674', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13123/']