Thursday, December 6, 2007

JMX Managed Bean with multiple agents

Thursday, December 06, 2007 Posted by Andre Broers 4 comments
In this example I created a counter that gets updated from multiple instances. All examples I found on internet are using a single agent instance. The crux is to create a static MBean object that is available to all instances of the agent class. Let's get to the code:

/home/broersa/work/mbean/mypack/MyCounterMBean.java

[sourcecode language="java"]

package mypack;
public interface MyCounterMBean {
   public int getCounter();
   public void sayCounter();
}
[/sourcecode]

/home/broersa/work/mbean/mypack/MyCounter.java

[sourcecode language="java"]

package mypack;

public class MyCounter implements MyCounterMBean {
   private int counter = 0;

   public MyCounter() {
      counter = 0;
   }

   public int getCounter() {
      return counter;
   }

   public void incCounter() {
     counter++;
   }

   public void sayCounter() {
      System.out.println(counter);
   }
}
[/sourcecode]

/home/broersa/work/mbean/mypack/SimpleAgent.java

[sourcecode language="java"]

package mypack;

import javax.management.*;
import java.lang.management.*;

public class SimpleAgent {
   private static MyCounter counterBean = new MyCounter();
   private MBeanServer mbs = null;

   public SimpleAgent() {

      // Get the platform MBeanServer
       mbs = ManagementFactory.getPlatformMBeanServer();

      // Unique identification of MBeans
      // replaced by static var.     Hello helloBean = new Hello();
      ObjectName myCounterName = null;

      try {
         // Uniquely identify the MBeans and register them with the platform MBeanServer
         myCounterName = new ObjectName("SimpleAgent:name=MyCounter");
         mbs.registerMBean(counterBean, myCounterName);
      } catch (InstanceAlreadyExistsException e) {
         System.out.println("Instance Already Exists");
      } catch(Exception e) {
         e.printStackTrace();
      }
      counterBean.incCounter();
   }

   // Utility method: so that the application continues to run
   private static void waitForEnterPressed() {
      try {
         System.out.println("Press  to continue...");
         System.in.read();
      } catch (Exception e) {
         e.printStackTrace();
      }
    }

   public static void main(String argv[]) {
      SimpleAgent agent1 = new SimpleAgent();
      SimpleAgent agent2 = new SimpleAgent();
      System.out.println("SimpleAgent is running...");
      SimpleAgent.waitForEnterPressed();
   }
}
[/sourcecode]

goto the directory mbean and compile the code:

javac -d . mypack/MyCounter.java

javac -d . mypack/SimpleAgent.java

run the code:

java -Dcom.sun.management.jmxremote mypack.SimpleAgent

Instance Already Exists
SimpleAgent is running...
Press  to continue...

When we connect to the MBeanServer using the jconsole utility we see the counter has the value 2:

JConsole sample

4 comments: