Search code examples
javathreadpool

How to get the utilization rate of thread's current memory in java interface


How to get the utilization rate of thread's current memory in java interface? What classes and methods do you need to use?


Solution

  • This is not specifically about the utilization rate of a thread's memory. I am not sure about that.

    I have included here code that I used to pull similar statistics sometime back. Mine is JDK 8 on Windows.

    It prints the allocated bytes for the current thread from the local VM.

    The code that shows how one could connect to a remote JVM is included only to show that it is possible. But I don't show how to pull the same information from a remote JVM. It should give you some ideas.

    Moreover it uses com.sun.management.ThreadMXBean which I think is generally not recommended. I also don't know how valid the allocated bytes information is when it is actually pulled.

    import javax.management.MBeanServerConnection;
    import javax.management.remote.JMXConnector;
    import javax.management.remote.JMXConnectorFactory;
    import javax.management.remote.JMXServiceURL;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.StringWriter;
    import java.lang.management.ManagementFactory;
    import java.lang.management.ThreadMXBean;
    
    public class ThreadProbe{
    
        /* This code gives an idea about how to access a remote JVM */
        MBeanServerConnection connectJMXRemote(int port){
            JMXServiceURL url;
            MBeanServerConnection remote = null;
            try {
                url = new JMXServiceURL(
                        "service:jmx:rmi:///jndi/rmi://localhost:" + port + "/jmxrmi");
                JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
                remote = jmxc.getMBeanServerConnection();
                System.out.println("Remote JMX connection is successful");
            } catch (IOException e) {
                System.out.println(getStackTrace(e));
            }
            return remote;
        }
        public  void getThreadStatistics() {
    
            /* This code gives an idea about how to access a remote JVM */
            //MBeanServerConnection mbs = connectJMXRemote(9010);
    
            ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
            System.out.println( ((com.sun.management.ThreadMXBean)threadBean).
                                        getThreadAllocatedBytes(Thread.currentThread().getId()) );
        }
    
        String getStackTrace(Throwable t){
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            t.printStackTrace(pw);
            return sw.toString();
    
        }
    
        public static void main( String... argv ){
            ThreadProbe tp =new ThreadProbe();
            tp.getThreadStatistics();
        }
    }