Search code examples
javajmxjboss5.xmbeans

How to get a MBean binding class instance


I am trying to get the instance of a service class bound in jboss-service.xml using MBean.

JBoss-Service.xml has defined a BasicThreadPool which we want to use it in our code. This is what it is in JBOSS-Service.xml.

  <mbean 
        code="org.jboss.util.threadpool.BasicThreadPool"
        name="jboss.system:service=ThreadPool">

  <attribute name="Name">JBoss System Threads</attribute>
  <attribute name="ThreadGroupName">System Threads</attribute>
  <attribute name="KeepAliveTime">60000</attribute>
  <attribute name="MaximumPoolSize">10</attribute>

  <attribute name="MaximumQueueSize">1000</attribute>
  <!-- The behavior of the pool when a task is added and the queue is full.
  abort - a RuntimeException is thrown
  run - the calling thread executes the task
  wait - the calling thread blocks until the queue has room
  discard - the task is silently discarded without being run
  discardOldest - check to see if a task is about to complete and enque
     the new task if possible, else run the task in the calling thread
  -->
  <attribute name="BlockingMode">run</attribute>
   </mbean>

I am trying to access this in my code as below,

MBeanServer server = MBeanServerLocator.locateJBoss();          
MBeanInfo mbeaninfo = server.getMBeanInfo(new ObjectName("jboss.system:service=ThreadPool"));

Now I have the MBean Info. I want to have an instance of the BasicThreadPool object defined in the MBean. Is it possible ?

I know a way, we can get the class name from the MBean Info and also we can get the attributes by which we can construct an instance. Is there any better way of doing it ?


Solution

  • As skaffman indicated, you cannot directly acquire a direct instance of the thread pool, but using a MBeanServerInvocationHandler will get you pretty close.

    import org.jboss.util.threadpool.BasicThreadPoolMBean;
    import javax.management.MBeanServerInvocationHandler;
    import javax.management.ObjectName;
    .....
    BasicThreadPoolMBean threadPool = (BasicThreadPoolMBean)MBeanServerInvocationHandler.newProxyInstance(MBeanServerLocator.locateJBoss(); new ObjectName("jboss.system:service=ThreadPool"), BasicThreadPoolMBean.class, false);
    

    The threadPool instance in that example now implements all the methods of the underlying thread pool service.

    Mind you, if you only need it to submit tasks for execution, there's only one thing you need and that's the Instance attribute which is [pretty much] the same interface, so you could also do this:

    import  org.jboss.util.threadpool.ThreadPool;
    import javax.management.ObjectName;
    .....
    ThreadPool threadPool = (ThreadPool)MBeanServerLocator.locateJBoss().getAttribute(new ObjectName("jboss.system:service=ThreadPool"), "Instance");
    

    .... but not remotely though, only in the same VM.