Memory management has always been a powerful advantage of Java's advocacy. Developers simply need to create objects, and Java's garbage collector will automatically manage the allocation and deallocation of memory space. But in many cases, things are not that simple, and memory leaks are always occurring frequently in Java programs (Leaks).
What is a memory leak?
Memory leak definition: When some objects are no longer used by the application, but because they are still referenced, the garbage collector cannot release (remove, remove) them.
In the vernacular, it is: the recovered memory is not recycled , finally because the memory is not enough to cause the program error.
To understand this definition, we need to understand the state of the objects in memory. Shows what is not used, and what parts are not referenced.
Figure 1
As you can see, there is a reference object in memory, and no reference to the object. Objects that are not referenced are reclaimed by the garbage collector, and objects that are referenced are not garbage collected. Because no other object is referenced, the unreferenced object must be no longer used. But some of the useless objects are still being (unintentionally) quoted. This is the source of the memory leaks that occur.
Why is memory leaking?
Let's look at the following example to see why memory leaks. In the following scenario, object A refers to object B. A's life cycle (T1-T4) is much longer than B's (T2-T3). Object A still holds a reference to B when object B is no longer used in the application logic. (according to the virtual machine specification) In this scenario, the garbage collector cannot release B from memory. This situation is likely to cause memory problems, and if a also holds references to other objects, then these referenced (useless) objects are not recycled and occupy memory space.
It is even possible that B also holds a large heap of references to other objects. These objects are not recycled by the garbage collector because they are referenced by B. All of these useless objects will consume a lot of valuable memory space.
Figure 2
How to prevent memory leaks?
To prevent memory leaks, here are some quick tips for getting started:
1. Beware of collection classes, such as Hashmap,arraylist, as this is the place where memory leaks are most likely to occur. When collection objects are declared static, their life cycles are generally as long as the entire application.
2. Watch for event snooping and callbacks. When a registered listener is no longer in use, a memory leak is likely to occur if it is not logged off.
3. "When a class manages its own memory space, the programmer should be aware of memory leaks." Often a member variable of an object needs to be set to NULL when it still points to other objects.
Reference: http://blog.csdn.net/renfufei/article/details/14138099
http://blog.csdn.net/renfufei/article/details/14669513
Java memory Leaks (i)