A key advantage of the Java language is its memory management mechanism. You just create objects, and Java's garbage collector helps you allocate and reclaim memory. However, the actual situation is not that simple, because memory leaks still occur in Java applications.
The following explains what a memory leak is, why it happens, and how we can prevent it from happening.
1. What is a memory leak?
Definition of memory leak: Objects are no longer used by the application, but the garbage collector cannot remove them because they are still being referenced.
To understand this definition, we need to first understand the state of the object in memory. The picture below explains what a useless object is and what an unreferenced object is.
As you can see from the picture above, there are referenced objects and unreferenced objects. Unreferenced objects will be collected by the garbage collector, but referenced objects will not. An unreferenced object is of course an object that is no longer used, because no object refers to it anymore. However, useless objects are not all unreferenced objects. Some of them are cited. It is this situation that causes memory leaks.
2. Why does a memory leak occur?
Let’s first look at the following example to see why a memory leak occurs. In the following example, object A refers to object B. The life cycle of object A (t1-t4) is much longer than the life cycle of object B (t2-t3). When the B object is not used by the application, the A object still refers to the B object. In this way, the garbage collector cannot remove the B object from the memory, causing memory problems, because if A references more such objects, more unreferenced objects will exist and consume memory space.
Object B may also hold many other objects, and these objects will also not be recycled by the garbage collector. All these unused objects will continue to consume the previously allocated memory space.
3. How to prevent memory leaks from occurring?
Here are a few easy-to-use suggestions to help you prevent memory leaks from occurring.
Pay special attention to some collection objects like HashMap and ArrayList, which often cause memory leaks. When they are declared static, their lifetime is as long as the application.
Pay special attention to event listening and callback functions. A listener is registered while it is in use, but is not unregistered when it is no longer in use.
"If a class manages its own memory, developers have to be careful about memory leaks." Usually some member variables refer to other objects and need to be left blank during initialization.
A small question: Why is the substirng() method in JDK6 prone to memory leaks?
To answer the above question, you may want to take a look at Substring() in JDK 6 and 7.