One of the most obvious advantages of AVA is its memory management mechanism. You only need to simply create objects, Java's garbage recovery mechanism is responsible for allocating and release memory. However, the situation is not as simple as imagined, because memory leaks often occur in Java applications.
This tutorial demonstrates what is memory leak, why there is memory leakage and how to prevent memory leakage.
What is memory leakage?
Definition: If objects are no longer used in applications, but because they are cited elsewhere, garbage recycling cannot be removed (this causes a lot of memory to be unreasonable, resulting in memory overflow. Translation).
To understand this definition, we need to understand the state of the object in the memory. The figure below shows those who are not used, and those are not cited.
From the figure, we can see the reference object and the unprepared object (range). No cited object may be recycled by the garbage recycling mechanism, and the reference object cannot be recycled by the garbage recovery mechanism. Of course, the target is not used because there are no other objects quoting it. However, not all objects are not cited. Some unused objects are still cited elsewhere! This is the cause of memory leakage.
Why does memory leakage occur?
Let's come to this example below to see why the memory leak occurs. In the following example, the A object references the B object. A's life cycle (T1-T4) is much longer than the life cycle (T2-T3) of B. When B is no longer used in the application, A still holds the reference to B. In this way, the garbage recovery mechanism cannot remove B from memory. This is likely to cause memory spillover, 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 that B holds a large number of references to other objects. These objects referenced by B will not be recycled. All these unused objects will consume precious memory space.
How to prevent memory leaks?
The following is some fast skills to prevent memory leakage:
1. Pay attention to the collection class, 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 the life cycle of the application.
2. Pay attention to the incident monitor and callback. If a class is registered with a listener, but when the category is no longer used, the monitoring device may be not canceled, and memory leaks may occur.
3. "If a class manages his own memory, programmers should be alert to memory leakage." [1], many times the pointed to other object members in the object needs to be set to NULL (to be recycled).