I want my application to profile itself and tell me where memory allocation is taking place. Profilers are able to do that, so my application should be able to do that somehow too. How do profilers trap object instantiation and how can I do it myself?
You can do that by using -javaagent to pass instrumentation code into the JVM. We actually use this technique to find instance leaks in our applications. Below an example:
ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<String>();
String s = new String("hi");
MemorySampler.start();
queue.offer(s);
MemorySampler.end();
if (MemorySampler.wasMemoryAllocated()) MemorySampler.printSituation();
Outputs:
Memory allocated on last pass: 24576
Memory allocated total: 24576
Stack Trace:
java.util.concurrent.ConcurrentLinkedQueue.offer(ConcurrentLinkedQueue.java:327)
TestGC.main(TestGC2.java:25)
Where you can see that the object allocation happens on line 327 of ConcurrentLinkedQueue.
Disclaimer: I work for Coral Blocks which develops the MemorySampler class above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With