Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The <code>ManagementFactory</code> gives you a <code>java.lang.management.ThreadMXBean</code>, but the method you want to call is inside the <code>com.sun.management.ThreadMXBean</code> interface (which extends the <code>java.lang.management.ThreadMXBean</code> interface).</p> <p>If your are running on a Sun/Oracle VM, you can cast the result and call the method:</p> <pre><code>((com.sun.management.ThreadMXBean)ManagementFactory.getThreadMXBean()) .getThreadAllocatedBytes(); </code></pre> <p>But of course this will fail on other VMs. Also the com.sun package is not recommended to be used, because classes there might change at any time (even at minor updates to the VM). So it's best to be careful when using this and making your code not relying on it.</p> <p><em><strong>Edit</em></strong> If you still can't compile this, but it works using reflection, there is a nicer way than reflection. The Java Management API has special support for accessing beans and attributes by names, because it is very often that you want to display them without knowing of them at compile time (think of a generic JMX client like JConsole or VisualVM).</p> <p>Use the following code:</p> <pre><code>ObjectName threadMxBean = new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME); MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); long[] memUsedPerThread = (long[]) mbeanServer.getAttribute(threadMxBean, "ThreadAllocatedBytes"); </code></pre> <p>This should work, but I cannot test it, because on my JVM, the attribute is not there. If it does not work, use JConsole or VisualVM, connect to your Java process and verify that the attribute is indeed there with the correct name.</p> <p>You can also have a look at the <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/jmx/index.html" rel="nofollow">JMX documentation</a>.</p> <p><em><strong>Edit 2</em></strong> In your code example, you used <code>getThreadAllocationBytes</code>, but the link to the API shows <code>getThreadAllocatedBytes</code>. Double-check that you got that right. It was wrong in my answer, I fixed it now.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload