How to Profile JVM memory in the code?

后端 未结 5 1731
既然无缘
既然无缘 2021-01-03 09:24

I am writing a servlet that I can\'t test in Eclipse, I need to run on server. I want to do memory profiling and pinpoint any leaks. So, I think I need write debug statement

5条回答
  •  醉梦人生
    2021-01-03 10:12

    So, I think I need write debug statements that can tell me current memory usage.

    I think you are like me who prefers to profile in code instead of using an external profiling tool like JVisualVM or JConsole.

    You can use a tool called MemorySampler (written by me) from CoralBits that will tell you exactly in what line of your code memory is being allocated. Below an example:

    ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue();
    MemorySampler.start();
    for(int i = 0; i < strings.length; i++) queue.offer(strings[i]);
    for(int i = 0; i < strings.length; i++) queue.poll();
    MemorySampler.end();
    if (MemorySampler.wasMemoryAllocated()) MemorySampler.printSituation();
    

    Gives you the following output:

    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)
    

    Now if you go to line 327 of the ConcurrentLinkedQueue source code, you will see that it allocates a Node instance there.

    Disclaimer: I am one of the developers of CoralBits.

提交回复
热议问题