Reputation: 361
I want to know when and how many times an object is being used when a program is running. Do I need to access the JVM stack for that or there is another way to do the same?
Upvotes: 0
Views: 150
Reputation: 42441
What do you mean by "how many times an object is being used"? Is it how many times (one of) its constructors have been called? Or its how many times the object's methods were invoked? Please clarify...
In any case, there are a couple of ways to do that.
You can use your favourite profiler, I think you'll need to use a "tracing" mode (the mode that does an instrumentation, and not a sampling mode).
If recompiling the class is an option than you can do the following: Say, you have class Foo with some constuctors:
public class Foo {
public Foo(int i) {
// some constructor
}
public Foo(String s) { // another constructor }
}
Say, you want to know how many times your constructors were called (that is how many times the object have been created)
So, you can use a static data member and increase the count each time you call the constructor. Like this:
public class Foo {
private static int count = 0;
public Foo(int i) {
// if we're here, the object is being created now:
count++;
.....
}
...
}
Then you can take a heap snapshot (for example with jmap which resides in JAVA_HOME/bin) The generated dump can be opened by jhat or again your favourite profiler and you'll be able to see by exploring the object state.
Of course this approach holds for method invocations as well. It would work as long as your objects are created by the same class loader in fact.
3.If you can't recompile your code but still would not like to use a profiler, you can instrument your bytecode to achieve the same effect as in 2. You can consider to use frameworks like AspectJ here, there are a lot of others...
I think that the profiler is the quickest approach here Hope this helps
Upvotes: 1
Reputation: 47913
You need to use a profiler to do that. Something like YourKit or JProfiler or VisualVM.
Upvotes: 6