Is it possible to count the number of instances created for a class without having each instance to cooperate and tell some global/static data that it has been created. That is, can we count the number of instances and optionally get hold of a reference to it from a 3rd party class. For example, profilers can in general count the number of instances created from a class and display the fields values within each instance. How do profilers achieve this?
Pradeep Kumar
Ranch Hand
Joined: Sep 08, 2006
Posts: 108
posted
0
Yes you can count the number of instance created and also control them externally. One way of doing that is by creating the instances and registering them in the MBeanServer and monitoring them using jconsole. You need to do some backgroung work to make the Class an MBean. i.e the class whose instances you need to monitor. Have a look at the JMX specification. I would suggest you for using StandardMBean for monitoring for your use.
Hope this helps you :-)
Thanks and Regards, Pradeep Kumar
SCJP 1.6, SCWCD 5.0
Alec Lee
Ranch Hand
Joined: Jan 28, 2004
Posts: 568
posted
0
Hi Pradeep,
What about if the class was not created by the one doing the monitoring . For example, in profilers like VisualVM, we can attach it to any running jvm and monitor any class instance in it without having to first modify the classes to implement MBean (it seems to me that a JMX Manageable Resource have to be a class implement some JMX specific intefaces, right?).
John Pradeep.v
Ranch Hand
Joined: Jul 21, 2008
Posts: 59
posted
0
Hi Alec,
I think you can achieve this using AOP (AspectJ load time weaving) to point cut any object creation and expose the statistics through JMX MBean.
you can have a look at AspectJ load time weaving for better idea.
John
Pradeep Kumar
Ranch Hand
Joined: Sep 08, 2006
Posts: 108
posted
0
John Pradeep.v wrote:Hi Alec,
I think you can achieve this using AOP (AspectJ load time weaving) to point cut any object creation and expose the statistics through JMX MBean.
you can have a look at AspectJ load time weaving for better idea.
John
Hi John nice to see you here. I just had a chat with you in the evening. :-)
Hi Alec,
One more way would be to extend the class and implement the JMX interfaces and expose this class as MBean. Within the methods of the subclass just delegate it to the super class by using super. Let me know if this work out for you.
Also if you are using Spring you can go ahead and expose this as MBean as Spring can expose any bean as MBean. Advantage: you need not have to implement any JMX interfaces ;-)