/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:
