tags:

views:

63

answers:

1

While studying about JMX, I have seen one of the important feature of it is that it can manage a JVM itself, which i didn't understand about in what sense it can manage JVM. So can anybody elaborate this with some examples.

+2  A: 

You can see this for yourself very easily.

  • Step 1: Download JConsole
  • Step 2: Start a Java Process (Java 5 or later)
  • Step 3: Connect to your Java process with JConsole
  • Step 4: View the MBeans for triggering a heap dump event, a garbage collection request, thread information, loaded classes, etc

Whats particularly interesting is that you can write code to access the MBeans of a running Java program:

There are three different ways to access the management interfaces. Call the methods in the MXBean directly within the same Java virtual machine.

RuntimeMXBean mxbean = ManagementFactory.getRuntimeMXBean();

   // Get the standard attribute "VmVendor"    String vendor = mxbean.getVmVendor();

Go through a MBeanServerConnection connecting to the platform MBeanServer of a running virtual machine.

MBeanServerConnection mbs;

   // Connect to a running JVM (or itself) and get MBeanServerConnection  // that has the JVM MXBeans registered in it    ...

   try {
       // Assuming the RuntimeMXBean has been registered in mbs
       ObjectName oname = new ObjectName(ManagementFactory.RUNTIME_MXBEAN_NAME);

       // Get standard attribute "VmVendor"
       String vendor = (String) mbs.getAttribute(oname, "VmVendor");   } catch (....) {
       // Catch the exceptions thrown by ObjectName constructor
       // and MBeanServer.getAttribute method
       ...    }

Use MXBean proxy.

MBeanServerConnection mbs;

   // Connect to a running JVM (or itself) and get MBeanServerConnection  // that has the JVM MBeans registered in it    ...

   // Get a MBean proxy for RuntimeMXBean interface    RuntimeMXBean proxy = 
       ManagementFactory.newPlatformMXBeanProxy(mbs,
                                                ManagementFactory.RUNTIME_MXBEAN_NAME,
                                                RuntimeMXBean.class);    // Get standard attribute "VmVendor"     String vendor = proxy.getVmVendor();

See also The Java Language Management API

Amir Afghani