Java Memory Leak

Memory leaks Cause memory overflow Memory leaks are classified into four types

  • Frequent memory leaks

The code that leaks memory is executed multiple times, causing a memory leak each time it is executed.

  • Occasional memory leak

Memory leaks occur later in the code in a specific environment or during operations;

  • One-time memory leak

The code that leaks is executed only once, or because of a flaw in the algorithm, one and only one piece of memory is always leaked.

  • Implicit memory leaks

The program allocates memory variously as it runs, but does not release it until it finishes.

Causes of Java memory leak Memory leak refers to the waste of memory space caused by useless objects occupying the memory continuously or the memory of useless objects cannot be released in a timely manner.

Root cause, long-life objects hold references to short-life objects;

  • Static collection classes cause memory leaks

The lifetime of these static variables is the same as that of the application. All objects referenced by them cannot be freed because they will always be referenced by vectors. The remove() method does not work when the properties of objects in the collection have been modified;

  • The listener

The listener is not removed when the object is released, increasing the chance of memory leaks.

  • All kinds of connection

Database connections, network connections, and IO connections are not automatically collected by GC unless they are displayed calling their close() method.

  • The singleton pattern

If the singleton pattern holds a reference to an external object, that external object cannot be properly reclaimed by the JVM, resulting in a memory leak.