Analysis of memory leakage in Java
One of the most obvious advantages of AVA is its memory management mechanism. You simply create objects, and Java's garbage collection mechanism is responsible for allocating and freeing memory. However, the situation is not as simple as expected, because memory leaks often occur in Java applications.
This tutorial demonstrates what a memory leak is, why it occurs, and how to prevent it.
What is a memory leak?
Definition: if objects are no longer used in an application, but they are referenced elsewhere, garbage collection cannot remove them.
To understand this definition, we need to understand the state of objects in memory. The following figure illustrates those that are unused and those that are not referenced.
You can see referenced and unreferenced objects from the figure (scope of). Unreferenced objects can be recycled by the garbage collection mechanism, while referenced objects cannot be recycled by the garbage collection mechanism. Unreferenced objects are certainly unused because no other objects refer to them. However, unused objects are not always unreferenced. Some unused objects are still referenced elsewhere! This is the cause of memory leakage.
Why does a memory leak occur?
Let's take the following example to see why a memory leak occurs. In the following example, the a object references the B object. The life cycle of a (T1-T4) is larger than that of B (T2-T3) is much longer. When B is no longer used in the application, a still holds a reference to B. in this way, the garbage collection mechanism cannot remove B from memory. This is likely to lead to memory overflow, because if many other objects are like a, there will be many objects that cannot be recycled in memory, which will consume a lot of memory space. It is also possible B holds a lot of references to other objects. These objects referenced by B are also not recycled. All these unused objects will consume valuable memory space.
How to prevent memory leaks?
Here are some quick tips to prevent memory leaks:
1. Pay attention to collection classes, such as HashMap, ArrayList, etc., because they are where memory leaks often occur. When they are declared as static objects, their life cycle is as long as that of the application.
2. Pay attention to event listeners and callbacks. If a class registers a listener, but does not unregister the listener after the class is no longer used, a memory leak may occur.
3. "If a class manages its own memory, programmers should be alert to memory leaks." [1] , many times, the member variables pointing to other objects in the object need to be set to null (to be recycled).