Memory management is one of the most important advantages of Java. You just need to create objects, and the Java garbage collector will automatically allocate and release memory. However, the situation is not so simple because memory leaks often occur in Java applications.
This chapter explains what memory leaks are, why they occur, and how to prevent them.
What is a memory leak?
Definition of a memory leak: objects that are no longer used by an application but cannot be deleted by the garbage collector because they are being referenced.
To understand this definition, we need to understand the state of an object in memory. The following figure shows what is not referenced and what is a referenced object.
As you can see from the diagram, there are referenced objects and unreferenced objects. Unreferenced objects will be garbage collected, and referenced objects will not be garbage collected. An unreferenced object is certainly unused because no other object references it. However, not all unused objects are not referenced, some of them are referenced! This is the source of the memory leak.
Why does a memory leak occur?
Let’s take a 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 a (T1-T4) is much longer than that of B (T2-T3). When B is no longer used in the application, a still has a reference to B, so the garbage collector cannot delete B from memory. This may lead to an out of memory problem, because if a does the same thing for more objects at the same time, many objects like B will not be collected and occupy memory space.
B may also have a bunch of references to other objects, and objects referenced by B will not be collected. All of these unused objects consume valuable memory space.
How to prevent memory leaks?
Here are some quick and practical tips for preventing memory leaks.
Pay attention to collection classes, such as HashMap, ArrayList, and so on, as they are common places to find memory leaks. When they are declared static, their lifetime is the same as that of the application.
Pay attention to event listeners and callbacks. If a listener is registered, but the class is no longer used, a memory leak may occur.
If a class manages its own memory, the program should be alert to memory leaks. In general, member variables pointing to other objects need to be null.
Why does the substring method in JDK 6 cause memory leaks?
Recent hot articles recommend:
Feel good, don’t forget to like + forward!