On Martin Gutenbrunner worked at Ruxit, it has 10 years of Java Web application architecture and management experience. Recently, he wrote a Java memory leak identification to share relevant experience in Dzone, translated by OneAPM engineer.
The following is a translation
Java developers know, Java garbage collection mechanism to automatically use application memory to keep clean and healthy. However, some people may not know is that even with the garbage collection mechanism, Java is still possible memory leak risk. If you get the following error code:
java.lang.OutOfMemoryError: Java heap space
If you're sure is insufficient memory allocation, then the following code can increase the available memory for the application:
java -Xms -Xmx
However, for the memory leak is doing is a temporary solution, can only play a role in mitigation.
Identify memory leaks
Before deployment into the production environment to check whether there is a memory leak problem it is necessary. Here we can make a preliminary judgment by the garbage collector indicators.
After GC as memory usage continues to rise, then it may have a memory leak problems, such as above this figure, the code can be viewed GitHub (https://gist.github.com/dpryden/b2bb29ee2d146901b4ae). But on the map as a linear memory as an increased likelihood in reality it is very small, Figure Old Gen, and GC suspension times or Eden Space and Survivor space usage and insufficient to identify memory leaks.
To find out the reasons for memory leaks the moment there are already many tools are available, such as JVisualVM or jStat. These tools are comes with the JDK, so we can use at any time. In addition to the identification of some common internal Java classes, some users also need to recognize custom tired.
In the daily development process, as long as the GC does not affect the performance, developers will not to pay attention to memory settings in the configuration. Thus planting the potential pitfalls: the problem is not only because the memory overflow and leak, GC time is too long will also cause this problem. For example, the following figure GC takes up 16% of the CPU.
Heap too small to cause frequent GC, thus not difficult to imagine the scene: the increase GC will consume more CPU, while JVM GC will be frozen in time, leading to a poor performance. Overall, Heap too small, although the GC time is shorter, but will become more frequent.
Heap too large lead time GC side. GC does not happen often, but once triggered, then the VM will be frozen for a long time.
Thus, if a memory leak in this case, because in the final JVM out of memory before the collapse, GC will be very frequent or particularly long time.
From Java 6 began, GC changed a lot. Java 7 introduced G1GC as an alternative CMS GC, whereas in Java 9 in G1GC has become the default choice. Java 8 are removed PermGen Space, the data previously stored in PermGen Space will be replaced in the local memory or stored on the stack.