Understanding and solving of Java memory leaks

Source: Internet
Author: User

Java Memory Management mechanism

In the C + + language, if you need to allocate a chunk of memory dynamically, programmers need to be responsible for the entire life cycle of this memory. From the application assignment, to the use, to the final release. The process is very flexible, but cumbersome, and the programmer is prone to inadvertently forget to release memory, resulting in memory leaks. The Java language has made its own optimizations for memory management, which is the garbage collection mechanism. Almost all memory objects in Java are allocated on heap memory (except for the base data type), and the GC (garbage collection) is responsible for automatically reclaiming memory that is no longer in use.

Above is the basic situation of the Java Memory management mechanism. But if we just understand this, we will still encounter memory leaks in the actual project development. Perhaps some people doubt that, since the Java garbage collection mechanism can automatically reclaim memory, how can there be a memory leak situation? This problem, we need to know when the GC reclaims memory objects, what kind of memory objects will be considered by the GC is "no longer used".

Access to memory objects in Java, using a reference method. In Java code we maintain a reference variable of a memory object, and through the value of the reference variable, we can access the memory object space in the corresponding memory address. In a Java program, the reference variable itself can be stored in heap memory and placed in the memory of the code stack (the same as the basic data type). GC threads start tracking from reference variables in the code stack to determine which memory is being used. If the GC thread is unable to trace a chunk of memory in this way, then the GC will assume that the memory is no longer in use (because the memory is inaccessible in the code).

With this graph-based approach to memory management, a GC can recycle a memory object after it loses all references. Conversely, if the object still has a reference, it will not be recycled by GC, even if the Java virtual machine throws OutOfMemoryError.

Java memory leaks

There are generally two kinds of memory leaks. A situation such as in the C + + language, the allocated memory in the heap, when it is not released, all the way to access the memory is deleted (such as pointer re-assignment), and the other is that the memory object is clearly not needed, still retains the memory and its access (reference). The first case, in Java has been due to the introduction of garbage collection mechanism, has been well resolved. So, the memory leak in Java, mainly refers to the second case.

Perhaps the concept of light is too abstract, you can look at this example:

Vector v = new vector (10);  for (int i = 1; i <, i + +) {Object o = new Object ();  V.add (o);  o = null; }

In this example, there is a reference to the vector object in the code stack with reference to the V and object o. In the For loop, we constantly generate new objects, add them to the Vector object, and then empty the O reference. The question is, if a GC occurs when the O reference is empty, can we create an object that is recycled by GC? The answer is in the negative. Because, when the GC traces a reference in the code stack, it discovers a V reference, and continues to trace, it finds that the memory space pointed to by the V reference has a reference to the object. This means that although the O reference is already empty, there are still other references to object objects that can be accessed, so the GC cannot release it. If after this loop the object object has no effect on the program, we assume that the Java program has a memory leak.

Although for &NBSP;JAVA&NBSP;  cpu &NBSP;JAVA&NBSP; &NBSP;OUTOFMEMORYERROR&NBSP;

Avoidance of memory leaks under normal circumstances

In general cases where complex data structures are not involved, Java's memory leaks behave as a memory object whose lifetime exceeds the length of time the program needs it. We also sometimes call it "object Free".

For example:

Public class filesearch{        private byte []  content;        private File mFile;        public filesearch (File file) {         mFile = file;        }        public boolean hasstring (STRING&NBSP;STR) {            int size = getfilesize (Mfile);           content =  new  byte [size];            loadfile (mfile, content);            string s =  new string (content);             return s.contains (str);        }  } 

to avoid a memory leak in this case, ask us to C + + Memory management Thinking to manage their own allocated memory. The first is to clarify the valid scope of the memory object before declaring the object reference. A memory object that is valid within a function should be declared as a local variable, the same as the life cycle of the class instance, to be declared as an instance variable ... And so on Second, when the memory object is no longer needed, remember to manually empty its reference.

Memory leak problems in complex data structures

java   A special mechanism to prevent memory leaks.

As we have described before, the GC mechanism ofJava is built on the reference mechanism for tracking memory. And before that, the references we used all just defined an " Object o; "In such a form." In fact, this is just one of the default cases in the Java reference mechanism, and there are other ways to refer to it. By using these special reference mechanisms, together with the GC mechanism, we can achieve some of the effects we need.


Understanding and solving of Java memory leaks

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.