directory

directory

What is a memory leak

2. Causes of memory leaks

2. What are the conditions of memory leaks

2.1 The memory cannot be reclaimed because the code is not released in time.

2.2 Memory Leakage caused by unclosed resources

2.3 Objects held by the Global cache are not removed when they are not in use. As a result, they cannot be removed from the memory

2.4 Static collection classes

2.5 Out-of-heap memory cannot be reclaimed

3. Solutions to memory leaks

4. Check memory problems

The first step is to identify the logical problem,

Step 2: Analyze whether gc executes normally

The third step is to confirm the changes of the new code in the next version and find out the problems from the code as soon as possible.

Step 4: Open various command lines and export dump various tools analysis

Conclusion:


What is a memory leak

A memory leak refers to a waste of memory space caused by unwanted objects (objects that are no longer in use) occupying the memory continuously or the memory of unwanted objects cannot be released in a timely manner. As the garbage collector activity increases and the memory footprint increases, the performance of the program gradually degrades and, in extreme cases, raises OutofMemoryErrors causing the program to crash.

2. Causes of memory leaks

The JVM uses reference counting and reachability analysis to determine whether an object is recyclable. In essence, it determines whether an object is still referenced, and if there is no reference, it is recycled. In the process of development, there will be many kinds of memory leakage problems due to the different implementation of the code, so that the GC system mistakenly believes that this object is still in reference, cannot be reclaimed, resulting in memory leakage.

2. What are the conditions of memory leaks

2.1 Memory could not be reclaimed because the code was not freed in time.

The following code, because it is a bidirectional linked list, is not broken completely enough, and the prev node still refers to the node that is currently in use, so it cannot be recycled

public class ListNode {    int val;    ListNode next;    ListNode prev;    ListNode() {    }    ListNode(int val) {        this.val = val;    }    public ListNode(int val, ListNode next, ListNode prev) {        this.val = val;        this.next = next;        this.prev = prev;    }

    public static void main(String[] args) {        ListNode curr = new ListNode(1);        ListNode prev = new ListNode(2);        ListNode next = new ListNode(3);        curr.prev = prev;        curr.next = next;        curr.prev = null;    }}
Copy the code

2.2 Memory leak caused by resource not being closed

 

You can use try-with-resources to automatically release resources after reading files from a database, network, or IO connection

try (RandomAccessFile raf = new RandomAccessFile(filePath, "r");) { Image image = null; while((image = parseImage(raf)) ! = null){ imageList.add(image); } return imageList; } catch(Exception e){ log.error("parse file error, path: {},", path, e); return null; }Copy the code

 

2.3 Objects held by the global cache are not removed in time when they are not in use. As a result, they cannot be removed from memory

 

2.4 Static collection class

Examples include HashMap, LinkedList, and so on. If these containers are static, their life cycle is consistent with that of the program, and objects in the container cannot be released until the program ends, resulting in a memory leak. A long-lived object holds a reference to a short-lived object, which cannot be reclaimed because the long-lived object holds a reference to it, although the short-lived object is no longer in use.

2.5 Out-of-heap memory cannot be reclaimed

Out-of-heap memory is not managed by GC and can leak due to third-party bugs

3. Solutions to memory leaks

1. Minimize the use of static variables or assign the value to NULL immediately after use.

2. Define the effective scope of the memory object, minimize the scope of the object, and use local variables to deal with non-member variables, because the local variable stack will automatically recycle;

3. Reduce long-lived objects holding short-lived references;

4. Use StringBuilder and StringBuffer to connect strings. Sting, StringBuilder and StringBuffer can all represent strings, where String represents immutable strings and the latter two represent mutable strings. If multiple strings are used for String concatenation, a large number of temporary strings can be generated at run time, which can be held in memory and lead to performance degradation.

5. Manually set null values for objects that are not needed. Whenever GC starts cleaning, we should mark useless objects as cleanable objects.

6. All kinds of connection (database connection, network connection, IO connection) operation, be sure to display the call close.

4. Check memory problems

No programmer wants to have this problem, but the problem should be solved. The main symptom of memory leak is insufficient memory, and how to determine whether there is a memory leak after the memory alarm.

The first step is to identify the logical problem,

Check whether the number and size of objects in memory are in a reasonable range. If they are in a reasonable range, increase the memory configuration and adjust the memory ratio.

Command:

 jmap -heap pid
Copy the code

Step 2: Analyze whether gc executes normally

Command:

jstat -gcutil <pid> 1000
Copy the code
 
Copy the code

S0 - percentage of used space on Survivor space 0 on the Heap S1 - percentage of used space on Survivor space 1 on the Heap E - percentage of used space on Eden space O - Percentage of used space in the Old space area on the Heap P - percentage of used space in the Perm space area YGC - Number of Young GC's occurring from application startup to sampling YGCT - Young GC's occurring from application startup to sampling Time spent in seconds FGC - Number of Full GC occurrences from application startup to sampling FGCT - Time spent in seconds from application startup to sampling Full GC GCT - Total time spent in garbage collection from application startup to sampling in seconds LGCC - Reasons for GC (earlier JDK versions may not have this column)Copy the code

From this point of view, you can also tune JVM memory allocation to improve performance and reduce the cost of GC to performance

The third step is to confirm the changes of the new code in the next version and find out the problems from the code as soon as possible.

Step 4: Open various command lines and export dump various tools analysis

-XX:+HeapDumpOnOutOfMemoryError
-XX:OnError
-XX:+ShowMessageBoxOnError
Copy the code
It is recommended to use JProfile for local analysis without having to remember so many commands.Copy the code

 

Conclusion:

Now although the server memory is very large, but and use and cherish, do not wait until there is a problem to know the consequences, in the development of the specification of their own code, used up the object timely release, reduce garbage objects. Don’t panic if something goes wrong. Analyze the code carefully. Everything happens for a reason.