停止Java内存泄漏

Java objects are stored in a memory area called the heap. This area increases and decreases in size, but has a limited space defined by several factors, depending on the Java version your application is running on. No matter how you reach that limit, you'll get an OutOfMemoryErrortype of error. If you increase the maximum memory allocation by setting the jvm parameter -Xmx and your application keeps hitting the limit and throwing this errors, it is very likely you have a memory leak.

当您的应用程序开始在内存中存储的对象超出了垃圾收集器的处理能力时,就会发生内存泄漏。 当没有引用时,可以通过垃圾收集器将其从内存中删除,这意味着您的应用程序正在保留对不再需要的对象的引用,或者需要以其他方式处理该对象以防止填满该对象。 堆。

Taking a heap dump

为了正确了解应用程序的内存管理中发生的事情,您需要做的第一件事就是堆转储。 您可以通过多种方式来实现这一目标。 第一个是通过在应用程序到达OutOfMemoryError。 您可以在启动应用程序时通过如下命令行选项启用该功能: java -XX:+ HeapDumpOnOutOfMemoryError -XX:HeapDumpPath = my / favorite / path MyApp

  • -XX:+ HeapDumpOnOutOfMemoryError使应用程序内存不足时,JVM会进行堆转储。-XX:HeapDumpPath =我/收藏夹/路径指定要保存转储的位置。

获取堆转储的另一种方法是使用映射JDK工具。 如果您的应用程序仅与JRE一起运行,则必须安装JDK,以便可以使用映射。 该命令的用法如下: 映射 -dump:format=b,file=heapdump.bin <process_id>

The options below are useful to perform analysis on a production environment, since you can extract the heap dump and copy the file over to your machine and load it into a tool. Another way to extract a heap dump is by attaching a tool to a running java application remotely. That involves using JMX, which in turn requires an open port, but if the application is running locally, in the same machine as your tool, you will see it listed:
停止Java内存泄漏
Once you are connected to the application, you will be able to load the heap dump. Refer to documentation and tutorials for each tool to learn how to take the heap dump.

Analyzing the data

After you have the heap dump, it's time to look into the data and determine what's causing the memory leak. The dump file can be analyzed with many tools, commercial, free and open source. I would recommend two tools: jvisualvm, and eclipse memory analyzer. If you have installed the JDK in your environment, you already have jvisualvm (it's in the bin directory). The eclipse memory analyzer (MAT) is an eclipse.org project, and can be downloaded from here.

Jvisualvm将为您提供加载的堆转储中最常用的对象的列表,这可以通过检查堆中有更多实例或占用最大字节量的对象来帮助识别内存泄漏。

If you decide to use MAT, I would highly suggest follow the process described in this blog post, in which the author describes the way the tool organizes the data and gives instructions on how to point down the culprit.

from: https://dev.to//pmadridb/stopping-a-java-memory-leak-35ae