Search code examples
javagarbage-collection

ThreadMXBean.getCurrentThreadAllocatedBytes Java 8 alternative?


In java 11 and up there's MXBeans.getCurrentThreadAllocatedBytes to get allocation information per thread, but this API isn't available in Java 8.

Is there any other way (without triggering a heap dump) I can get the allocation statistics per thread in Java 8?


Solution

  • From the documentation

    This is a convenience method for local management use and is equivalent to calling:
    getThreadAllocatedBytes(Thread.currentThread().getId());

    The linked method getThreadAllocatedBytes​(long id) does already exists in Java 8. Since com.sun.management.ThreadMXBean is a non-standard extension to java.lang.management.ThreadMXBean you may invoke the method dynamically, to avoid a hard-coded dependency:

    try {
      long bytes = (Long)ManagementFactory.getPlatformMBeanServer()
         .invoke(new ObjectName("java.lang:type=Threading"), "getThreadAllocatedBytes",
             new Object[] { Thread.currentThread().getId() }, new String[] { "long" });
      System.out.println(bytes);
    } catch(JMException ex) {
      ex.printStackTrace();
    }
    

    But if you use a build tool that doesn’t enforce restrictions, to use the official API only, the following would also work with Java 8 and the reference implementation:

    import java.lang.management.ManagementFactory;
    import com.sun.management.ThreadMXBean;
    
    public class MxTest {
      public static void main(String[] args) {
        ThreadMXBean tmxb = (ThreadMXBean)ManagementFactory.getThreadMXBean();
        long bytes = tmxb.getThreadAllocatedBytes(Thread.currentThread().getId());
        System.out.println(bytes);
      }
    }
    

    Note that there is a small possibility of failure due to the fact that getId() is not final and hence, a subclass of Thread could override it and return whatever it wants. That’s why JDK 19 has deprecated it and added a new final method threadId(). But in Java 8, you have to go with getId(). Just be aware of this possibility which hopefully never occurs.