user1870400 user1870400 - 6 months ago 32
Java Question

How to Monitor an existing Java class with JMX?

I have an existing Java class as follows and I want to monitor number of method invocations for each method in this class using JMX. How do I do it? I tried google but I can't see the big picture on how the whole thing is connected. It would be great if I can see see some code examples

Public class RPCServer {

public void storeSchema() { // want to count number of method invocations
System.out.println("storeSchema");
}

public void getSchema() { // want to count number of method invocations
System.out.println("getSchema");
}

public void storeRow() { // want to count number of method invocations
System.out.println("storeRow");
}

public void getRow() { //want to count number of method invocations
System.out.println("getRow");
}

}

Answer

First you need an interface for your class (is a shorter version of your class):

public interface RPCServerInterface {
  public void setRow(int i);
  public int getRow();
  int countMethodInvocation(String method);
}

Then I store how many time each function is call and I create a function to ask how many time that function is call.

public class RPCServer implements RPCServerInterface{
  private int row;
  private Map<String,Integer> countByMethod = new HashMap<String,Integer>();

  // +1 to the number of time of execution of this method
  private void sumMethodInvocation(String method) {
   if ( countByMethod.containsKey(method) ) {
     int n = countByMethod.get(method);
     countByMethod.put(method, n+1);
   } else {
     countByMethod.put(method,1);
   }
  }

  public int countMethodInvocation(String method){
    return countByMethod.get(method);
  }

  @Override
  public void setRow(int i) { 
    this.sumMethodInvocation("setRow"); 
    this.row = i;
  }
  @Override
  public int getRow() {
    this.sumMethodInvocation("getRow");
    return row;
  }
}}
} 

Then you have to register your Bean:

MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
RPCServer rpcServer =  new RPCServer();
ObjectName objectName = new ObjectName("org.foo.RPCServer.jmx:type=RPCServerInterface");

StandardMBean standardMBean = new StandardMBean(rpcServer,RPCServerInterface.class);
mBeanServer.registerMBean(standardMBean, objectName);

The path org.foo.RPCServer.jmx is arbitrary.

Then your run jconsole and you find the process you are running.

jconsole choose processs

Then you can run the command countMethodInvocation and you can get the number of execution time.

Like this:

Run program jconsole

This tutorial can be useful:

what-is-jmx-mbean-jconsole-tutorial

Comments