Detailed explanation of memory leakage in Java

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 recycle memory. However, the actual situation is not that simple, because memory leaks still occur from time to time in Java applications.

Let's explain what a memory leak is, why it happens, and how we can prevent it.

 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 referenced.

To understand this definition, we need to first understand the state of objects in memory. The following figure explains what useless objects are and what unreferenced objects are.

Unused and Unreferenced

As can be seen from the above figure, there are referenced objects and unreferenced objects. Unreferenced objects are collected by the garbage collector, while referenced objects are not. An unreferenced object is of course an object that is no longer used because no object references it. However, useless objects are not all unreferenced objects. There are also cited. It is this condition that causes a memory leak.

 2. 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, a object refers to B object, The life cycle of object a (T1-T4) is longer than that of object B (T2-T3) much longer. After the B object is not used by the application, the a object still references the B object. In this way, the garbage collector cannot remove the B object from memory, resulting in memory problems, because if a references more such objects, more unreferenced objects will exist and consume memory space.

B objects may also hold many other objects, which will not be collected by the garbage collector. All these unused objects will continue to consume the memory space allocated before.

Object-Life-Time

 3. How to prevent memory leakage?

Here are some easy-to-use suggestions to help you prevent memory leaks.

 4. A small question: why is the substirng () method in JDK6 prone to memory leakage?

To answer the above question, you may look at substring () in JDK 6 and 7.

Foreign language link: the introduction of JAVA memory leaks

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>