Java memory Leaks _ vs. C + + (reprint summary)

Source: Internet
Author: User

Original URL: http://developer.51cto.com/art/201111/302465.htm

Understanding and resolution of Java memory Leaks (1)

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 not needed, still retains the memory and its access mode (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.

AD:

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 J Ava, 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:
    1. vector v = new  vector ( 10 )  
    2. span class= "keyword" style= "background-color: #ffff00;" >for   ( int  i = 1 ;i  < 100 ; i ++ ) { 
    3. object o = new   object ();  
    4. v.add (o);  
    5. o = null ;  
    6. }&NBSP;

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.

Despite the small amount of damage caused by a Java memory leak in the case of memory leaks in C + +, in most cases the program will still run normally, except in the rare case of a program crash. However, when mobile devices have tighter limits on both memory and CPU, Java's memory overflow can lead to inefficient programs and high memory consumption. This results in a poor performance of the entire machine, which can also cause the outofmemoryerror to be thrown, causing the program to crash.

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:

  1. Public class filesearch{
  2. private byte [] content;
  3. private File Mfile;
  4. Public filesearch (file file) {
  5. Mfile = file;
  6. }
  7. Public boolean hasstring (String str) {
  8. int size = GetFileSize (mfile);
  9. Content = new byte [size];
  10. LoadFile (mfile, content);
  11. string s = new string (content);
  12. return S.contains (str);
  13. }
  14. }

In this code, there is a function hasstring in the FileSearch class to determine whether the document contains the specified string. The process is to load the mfile into memory first and then make a judgment. However, the problem here is that the content is declared in order to be an instance variable, not a local variable. Then, after this function returns, there is still data for the entire file in memory. It is clear that the data we follow is no longer needed, which creates an unwarranted waste of memory.

To avoid a memory leak in this case, we need to manage our own allocated memory in C + + memory management thinking. 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.

Java memory Leaks _ vs. C + + (reprint summary)

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.