Search code examples
javajmxmbeans

Getting all registered instances of own MBean


I have register my MBean app this way:

ObjectName appName = new ObjectName("testpack.Application:name=myApp");
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
mbs.registerMBean(this, appName);

And next I'm trying to get all registered instances by:

for (ObjectInstance instance : mbs.queryMBeans(appName, null)) {
    System.out.println(instance.toString());
}

But this prints only one instance even if I run many instances of this same app on this same JVM. What I misunderstood? How to do this properly?


EDIT

Excuse me, I misunderstood some basic terms like MBeans, JMX agents, servers and clients. Now I now that my app must be an JMX client and expose common MBean to do some kind of communication across my apps and maybe own managment console in future.

@Gray point me that I'm asking about some different that I want. Now I'm study JMX from basics and some aspects was clearly.


Solution

  • Edit:

    So now it seems that you are talking about multiple JVMs running on a box. By using the ManagementFactory.getPlatformMBeanServer() code, you are accessing the beans in the current JVM only. If you are trying to look at beans on another JVM instance then you are going to have to use a JMX client to connect to that remote process. Using my SimpleJMX package you could do something like:

    JmxClient client = new JmxClient("localhost", somePortNumber);
    Set<ObjectName> objectNameSet = client.getBeanNames();
    ...
    

    Here are the javadocs for my JmxClient. There are certainly others clients that do this. Java 6+ might even have them built in. I know that there are ways to programmatically list the JVM instances on the current computer in Java 6+. My SimpleJMX package does not do that.


    I'm not sure I understand the question but I think you are saying that you have multiple instances of your myApp class but you are only seeing one of them in JMX.

    You are going to have to create unique ObjectName for each of your classes if you want to see them separately via JMX. Typically, we use folders and bean names (sometimes even System.identityHashCode(obj)) to get a unique name for each instance of the object.

    For example, we have a large number of timer factory beans. They have object names like:

    mprew:00=timers,name=MailServerTimerFactory
    mprew:00=timers,name=MysqlManagerTimerFactory
    mprew:00=timers,name=PointsTimerFactory
    

    They all are the same class and we are using the spring bean to identify them specifically.