How to find a Java Memory Leak

后端 未结 11 1087
遇见更好的自我
遇见更好的自我 2020-11-22 07:48

How do you find a memory leak in Java (using, for example, JHat)? I have tried to load the heap dump up in JHat to take a basic look. However, I do not understand how I am s

11条回答
  •  猫巷女王i
    2020-11-22 07:53

    You can find out by measuring memory usage size after calling garbage collector multiple times:

    Runtime runtime = Runtime.getRuntime();
    
    while(true) {
        ...
        if(System.currentTimeMillis() % 4000 == 0){
            System.gc();
            float usage = (float) (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024;
            System.out.println("Used memory: " + usage + "Mb");
        }
    
    }
    

    If the output numbers were equal, there is no memory leak in your application, but if you saw difference between the numbers of memory usage (increasing numbers), there is memory leak in your project. For example:

    Used memory: 14.603279Mb
    Used memory: 14.737213Mb
    Used memory: 14.772224Mb
    Used memory: 14.802681Mb
    Used memory: 14.840599Mb
    Used memory: 14.900841Mb
    Used memory: 14.942261Mb
    Used memory: 14.976143Mb
    

    Note that sometimes it takes some time to release memory by some actions like streams and sockets. You should not judge by first outputs, You should test it in a specific amount of time.

提交回复
热议问题