Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to trap object allocation in Java inside your code through a method callback?

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?

like image 526
Michelle Queen Avatar asked Mar 07 '26 14:03

Michelle Queen


1 Answers

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.

like image 89
rdalmeida Avatar answered Mar 09 '26 04:03

rdalmeida