JMX example: A Java JMX Swing application

Here is some sample Java source code for some JMX tests that I created a while ago. I started my first tests with an introductory JMX tutorial, then created this JMX example to see how JMX might work with a standalone application, in this case, a Java Swing GUI application. Let's look at the code.

First, here's the source code for a Java interface (an MBean interface) named HelloMBean:

public interface HelloMBean {
  public void setMessage(String message);
  public String getMessage();
  public void sayHello();
}

Next, here's the source code for a Java class named Hello that implements the HelloMBean interface:

public class Hello implements HelloMBean {
  private String message = null;

  public Hello() {
    message = "HI there";
  }

  public Hello(String message) {
    this.message = message;
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public String getMessage() {
    return message;
  }

  public void sayHello() {
    System.out.println(message);
  }
}

Next up, here's the source code for a Java class named SimpleAgent2 that includes a main method that kicks off this JMX application and JMX service:

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

public class SimpleAgent2 {
   private MBeanServer mbs = null;

   public SimpleAgent2() {

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

      // Unique identification of MBeans
      Hello helloBean = new Hello();
      ObjectName helloName = null;

      try {
         // Uniquely identify the MBeans and register them with the platform MBeanServer 
         helloName = new ObjectName("FOO:name=SwingHelloThere");
         mbs.registerMBean(helloBean, helloName);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }

   public static void main(String argv[]) {
      SimpleAgent2 agent = new SimpleAgent2();
      System.out.println("SimpleAgent2 is running...");
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      f.setVisible(true);
   }
}

And finally here's a Unix/Linux shell script named run.sh that I wrote to run this sample JMX application:

#!/bin/sh

java -Dcom.sun.management.jmxremote \
     -Dcom.sun.management.jmxremote.port=1617 \
     -Dcom.sun.management.jmxremote.authenticate=false \
     -Dcom.sun.management.jmxremote.ssl=false \
     SimpleAgent

To run all of this code, save the source code shown here to the appropriate files (HelloMBean.java, Hello.java, and SimpleAgent2.java, and run.sh), compile them, and then run them with the run.sh script.

Once the application is running you can then connect to it with the jconsole application and view its JMX resources.