What is JMX? 10 mins Quick Start JMX Tutorial (MBean, JConsole)

Filed Under: Java

Java Management Extensions (JMX) was introduced in J2SE 5.0 release. It provides an architecture to manage resources dynamically at runtime. JMX is used mostly in enterprise applications to make the system configurable or to get the state of application at any point of time.

To manage any resource through JMX, we need to create Managed Beans (MBeans) and then register it to the MBean Server. MBean server works as a management agent for all the MBeans registered.

We use JMX Connectors to connect to MBean server and to manage the registered resources. For example, JDK comes with JConsole through which you can connect to any local or remote MBean server. If you have worked on JBoss server or any enterprise servers, they all comes with JMX Console to monitor and manage MBeans.

jmx, mbean, jconsole, jmx tutorial

Here we will learn basics of JMX and how to use JConsole to connect and manage MBeans. Lets start now…

First of all we need to create MBean and for that we need to first create the interface that defines the attributes and operations that we want to expose. The interface name must end with MBean. If you just want to allow read-only, you can leave setter methods.

SystemConfigMBean.java


package com.journaldev.jmx;

public interface SystemConfigMBean {

    public void setThreadCount(int noOfThreads);
    public int getThreadCount();
    
    public void setSchemaName(String schemaName);
    public String getSchemaName();
    
    // any method starting with get and set are considered
    // as attributes getter and setter methods, so I am 
    // using do* for operation.
    public String doConfig();
}

Next step is to provide the actual implementation of the MBean interface. The JMX Naming convention is to keep the implementation class name as interface name – MBean. So my implementation class will be SystemConfig.

SystemConfig.java


package com.journaldev.jmx;

public class SystemConfig implements SystemConfigMBean {

    private int threadCount;
    private String schemaName;
    
    public SystemConfig(int numThreads, String schema){
        this.threadCount=numThreads;
        this.schemaName=schema;
    }
    
    @Override
    public void setThreadCount(int noOfThreads) {
        this.threadCount=noOfThreads;
    }


    @Override
    public int getThreadCount() {
        return this.threadCount;
    }


    @Override
    public void setSchemaName(String schemaName) {
        this.schemaName=schemaName;
    }


    @Override
    public String getSchemaName() {
        return this.schemaName;
    }
    
    @Override
    public String doConfig(){
        return "No of Threads="+this.threadCount+" and DB Schema Name="+this.schemaName;
    }

}

Now we need to register our MBean implementation to the MBean server. We can keep any name of our class. After registering MBean, I will keep the thread running until we modify the thread count to 0 through jconsole, that will be the logic to end our application.

SystemConfigManagement.java


package com.journaldev.jmx;

import java.lang.management.ManagementFactory;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;

public class SystemConfigManagement {
    private static final int DEFAULT_NO_THREADS=10;
    private static final String DEFAULT_SCHEMA="default";

    public static void main(String[] args) throws MalformedObjectNameException, InterruptedException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException {
        //Get the MBean server
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        //register the MBean
        SystemConfig mBean = new SystemConfig(DEFAULT_NO_THREADS, DEFAULT_SCHEMA);
        ObjectName name = new ObjectName("com.journaldev.jmx:type=SystemConfig");
        mbs.registerMBean(mBean, name);
        do{
            Thread.sleep(3000);
            System.out.println("Thread Count="+mBean.getThreadCount()+":::Schema Name="+mBean.getSchemaName());
        }while(mBean.getThreadCount() !=0);
        
    }

}

When I run the above program, it registers our MBean implementation to the platform MBean server and keeps on printing following lines on console.


Thread Count=10:::Schema Name=default
Thread Count=10:::Schema Name=default
Thread Count=10:::Schema Name=default

Let’s start JConsole now and check all the options our MBean provides. To start JConsole, all you need to do is open a terminal window and run jconsole command.

JConsole allows to create local connection as well as connection to remote processes, you will be able to see our program name in the list of local processes. Just chose the application and click on Connect button, once connected go to MBean tab and you will see that we can change the value of threadCount and schemaName dynamically and any value changed there will be reflected in console where our application is running. We are also presented with the methods that we can invoke.

jconsole, jmx, jmx tutorial, jmx console, jmx api

As soon as you will change the threadCount to 0, the application will exit the do-while loop and terminate.

Some of the benefits of using JMX are:

  • JMX allows us to manage our application at runtime without any heavy investment and provides out of the box solution.
  • Using JMX is easy and reduces effort and investment for creating any management tool for our applications.

Comments

  1. vinayak says:

    Best explanation for a kick start

  2. lingaswamy says:

    Hello Pankaj,

    Could you please help me on this, when registering the Mbserver , the HtmlAdaptorServer methods coming default,But my case it’s not required to display, Below is code snippet.

    private HtmlAdaptorServer httpListener = null;
    private MBeanServer jmxServer = null;
    private boolean isStarted = false;

    public final void start() {
    try {
    final JmxManager applicationManager = getApplicationManager();
    applicationManager.startUp();
    jmxServer = applicationManager.getJmxServer();
    System.setProperty(JMX_LISTENER_LOGGING_LEVEL_SYSTEM_PROPERTY_KEY, getJmxTraceLevelFromProperty());
    System.setProperty(JMX_LISTENER_LOGGING_FILE_SYSTEM_PROPERTY_KEY, getJmxTraceFileName());
    com.sun.jmx.trace.TraceImplementation.init();
    httpListener = new HtmlAdaptorServer();
    httpListener.setPort(getListenerPortFromProperty());
    httpListener.addUserAuthenticationInfo(
    new AuthInfo(getListenerUserIdFromProperty(), getListenerUserPasswordFromProperty()));
    LOGGER.info(“Registering the Remove JMX listener with the JMX repository on port: ”
    + getListenerPortFromProperty());
    jmxServer.registerMBean(httpListener, new ObjectName(new StringBuffer().append(“Adaptor:”)
    .append(“name=”)
    .append(“jmxListener,”)
    .append(“port=”)
    .append(getListenerPortFromProperty())
    .toString()));
    httpListener.start();
    isStarted = true;
    LOGGER.info(“Started the Remove JMX listener”);
    } catch (final Exception e) {
    LOGGER.error(“Problem while registering and/or starting the Remove JMX listener.”, e);
    }
    }

  3. Doncho says:

    +1 But MBean have to be unregistered in a certain period

  4. Jerry Chin says:

    Nice and neat tutorial, I’m concerned aboutmemory leakage of JMX, will I need to deregister the MBean from MBeanServer to prevent it at the end of program?

  5. Sathishkumar says:

    Is any ways are available to print JConsole values?

  6. Nhat says:

    Great Job!!!

  7. Shankar says:

    Hi,
    It’s a very good article. I have one question
    1. What is Jconsole role here, is it agent or monitor?
    2. Who is acting as a MBean server ? If I run this on STS

  8. bhimesh says:

    Nice tutorial ๐Ÿ™‚

  9. name says:

    Nice one! Thank you. ๐Ÿ™‚

  10. Navin Goel says:

    Simple article to understand powerful concept. Thank you!

  11. Pramod Kanwar says:

    Wonderful description about JMX. It gave clear picture what JMX is and how we can use it. Looking forward to read your other articles :).

  12. Rakesh Shelar says:

    I am getting this error as i follow ur example

    NdsPlatform has identified runtime environment as JUnit.
    16:38:48,578 INFO xxx:[main] (ConfigReloader.java:94) – Config reload time changed to 300s
    javax.management.NotCompliantMBeanException: MBean class com.northgateps.nds.platform.loggingsystem.SystemConfig does not implement DynamicMBean, and neither follows the Standard MBean conventions (javax.management.NotCompliantMBeanException: Class com.northgateps.nds.platform.loggingsystem.SystemConfig is not a JMX compliant Standard MBean) nor the MXBean conventions (javax.management.NotCompliantMBeanException: com.northgateps.nds.platform.loggingsystem.SystemConfig: Class com.northgateps.nds.platform.loggingsystem.SystemConfig is not a JMX compliant MXBean)
    at com.sun.jmx.mbeanserver.Introspector.checkCompliance(Introspector.java:176)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:317)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:522)
    at com.northgateps.nds.platform.loggingsystem.SystemConfigManagement.(SystemConfigManagement.java:27)
    SimpleAgent is running…
    Press to continue…
    at com.northgateps.nds.platform.loggingsystem.SystemConfigManagement.main_aroundBody0(SystemConfigManagement.java:44)
    at com.northgateps.nds.platform.loggingsystem.SystemConfigManagement.main_aroundBody1$advice(SystemConfigManagement.java:105)
    at com.northgateps.nds.platform.loggingsystem.SystemConfigManagement.main(SystemConfigManagement.java:1)

  13. siva kumar says:

    Nice article

  14. Erick Andrade says:

    Excelent post!
    I had no idea what JMX was…but now I know what it is in 5 minutes!!! Thanks a lot Mr. Pankaj you’re good on it!

  15. Gourahari Sendha says:

    Very Nice !! Keep Posting … Great Job

  16. munimohan says:

    thanks alot Pankaj

  17. Adym says:

    Hi Pankaj, Great tutorial! One thing you might add as a Windows tidbit…If your MBean server application runs as Administrator, then you also need to run JConsole as Administrator.

    I discovered this, as my Eclipse IDE runs as Administrator. When I started JConsole from a Command prompt, I could see the MBean on the list, but I couldn’t connect to it. I had to start my Command Prompt > Run As Administrator…Then run JConsole and finally I could connect…

    hth,

    adym

    1. Pankaj says:

      Thanks for the comment, I think you covered it all. ๐Ÿ™‚

  18. HK says:

    It would be very useful if you can update the example with SSL? I could not find an example anywhere on how to do this with SSL.

  19. Dhiraj Kumar says:

    good example and explanation

  20. Kaibalya says:

    Thanks Pankaj for the beautiful explanation .But I am not a connect from Jconsole ,I am using windows 7.
    When I connect insecurely it simply says cannot connect.
    Do I have to do any setting changes.

    1. satish says:

      open up Jconsole ‘run as administrator’

  21. Danush says:

    Thank you. Very nice and simple!

  22. Ayo says:

    Thank you very much for the quick intro. Great job!

  23. Vishal says:

    Thanks a lot for this awesome explanation.

  24. rangaprakash says:

    i understand this application but i need to make how to think which operations need to run the different applications how to manage the different with jmx i need brief example the application managed by jmx

  25. Prithviraj Mane says:

    Thanks a lot Pankaj. It is very good example for starter’s like me .
    I have one question , can you give some exaple how we can expose JMX api vai apache camel

    1. Pankaj says:

      I am sorry but I haven’t worked on Apache Camel.

  26. Anurag Jain says:

    Seriously very good. Did not have any idea about JMX till now and the this tutorial gave me a decent confidence.

  27. Manoj says:

    Nice Example to Start . Thanks

  28. Girish says:

    Thanks Pankaj. After 10 years in java, this is the first tutorial I read about MBeans and it was crystal clear.

  29. Ravindra says:

    Excellent for getting started

  30. Abdul Rahim says:

    Excellent getting started tutorial and interesting too – keep posting please ๐Ÿ™‚

  31. Aayush says:

    Great explanation… Simple and effective!!!
    Thanks and keep going ๐Ÿ™‚

  32. Sumant Sharma says:

    it was really help full brother

  33. R World says:

    Very well explained ๐Ÿ™‚
    Thanks a lot Pankaj

  34. Mandar says:

    Thanks a lot ๐Ÿ™‚

  35. manikandan says:

    Thank you

  36. THirsty Soul says:

    just could not understand what JMX means till I hit this page…good article to start understanding about JMX

  37. mano says:

    very well explained

  38. Sonya says:

    Nice !. Helpful and understanding ! Thanks Bro ๐Ÿ™‚

  39. shrawan says:

    nice example to start.

  40. Arup Dutta says:

    Very nice introduction to JMX.

  41. Albert says:

    Great example to kickstart!

  42. tomabull says:

    Tks Pankaj,good job!

  43. Selman says:

    Thanks. Simple and clear

  44. Mohammad Banisaeid says:

    Thanks!
    Really helpful.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages