Understanding and solving of Java memory leaks

Source: Internet
Author: User

JavaMemory 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, aGC 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.

Javamemory 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), the other is in the memory object is clearly no longer required, It still retains the memory and the way it is accessed (referenced). 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:

 new  vector (10  );  2   int  i=1 ; I<100 ; I++ 3  Object o=new   Object ();  4   V.add (o);  5  o=null   6    

     In this example, there is a reference to the Vector object in the code stack v and a reference to the object Objects 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, when the o reference is empty, if a GC occurs, can we create a object to be recycled by GC ? The answer is in the negative. Because when GC traces a reference in the code stack, it finds a v reference, and continues to trace, it finds that the v reference points to a memory space that also points to the Object The reference to the object. This means that although the O reference is already empty, the object object still has other references that can be accessed, so 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 theprogram 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 classfilesearch{2  3     Private byte[] content;4     PrivateFile Mfile;5      6      Publicfilesearch (file file) {7Mfile =file;8     } 9 Ten      Publicboolean hasstring (String str) { One         intSize =GetFileSize (mfile); AContent =New byte[size]; -loadFile (mfile, content); -          theString s =NewString (content); -         returns.contains (str); -     } -}

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.

Memory leak problems in complex data structures

In actual projects, we often use some more complex data structures to cache the information needed for the program to run. Sometimes, because the data structure is too complex, or we have some special needs (for example, in case of memory permitting, as much as possible to cache information to improve the speed of the program, etc.), it is difficult for us to define the life cycle of data structure. At this point, we can use a special mechanism in Java to prevent memory leaks.

As we have described before, the GC mechanism of Java is built on the reference mechanism for tracking memory. And before that, the references we used all just defined an "Object o;" 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.

JavaSeveral reference methods in the

There are several different ways of referencing in Java: Strong, soft, weak, and virtual. Below, we begin with a detailed understanding of the implications of these kinds of citation methods.


Strong references

The references we used earlier in this article were strong references, which are the most common references. If an object has a strong reference, it is similar to essential necessities, and the garbage collector will never recycle it. When there is not enough memory space, theJava virtual machine prefers to throw a outofmemoryerror error, which causes the program to terminate abnormally, and does not rely on random recycling of strongly referenced objects to resolve out-of-memory issues.

Soft references (softreference)

A typical use of the SoftReference class is for memory-sensitive caches. The principle of softreference is to ensure that all soft references are purged before the JVM reports an out-of-memory condition while maintaining a reference to the object . The key is that the garbage collector may (and may not) release soft-and-accessible objects at run time. Whether an object is disposed depends on the algorithm of the garbage collector and the amount of memory available when the garbage collector is running.

Weak references (weakreference)

A typical use of the WeakReference class is normalized mapping (canonicalized mapping). In addition, weak references are useful for objects that have a relatively long lifetime and are not expensive to recreate. The key is that when the garbage collector runs, if it encounters a weakly accessible object, the object referenced by WeakReference is freed. Note, however, that the garbage collector may have to run multiple times to find and release a weak and accessible object.

Virtual reference (phantomreference)

The Phantomreference class can only be used to track the upcoming collection of referenced objects. Again, it can be used to perform Pre-mortem cleanup operations. phantomreference must be used with the Referencequeue class. Referencequeue is required because it can act as a notification mechanism. When the garbage collector determines that an object is a virtual object, thephantomreference object is placed on its referencequeue . placing the Phantomreference object on Referencequeue is also a notification that the object referenced by the Phantomreference object has ended and is ready for collection. This allows you to take action just before the memory that the object occupies is recycled. Reference is used in conjunction with Referencequeue.

Gc, The interaction of Reference and Referencequeue

A, The GC cannot delete the memory of an object that has a strong reference.

B, GC found a soft reference to the object memory, then:

The referent field of the ①softreference object is set to null, so thatthe object no longer references the heap object.

the heap object referenced by ②softreference is declared as finalizable.

③ when the Finalize () method of the heap object is run and the memory occupied by the object is freed, thesoftreference object is added to its referencequeue (if the latter exists).

C, The GC discovers an object memory with only a weak reference, then:

The referent field of the ①weakreference object is set to null, so that the object no longer references the heap object.

the heap object referenced by ②weakreference is declared as finalizable.

③ when the Finalize () method of the heap object is run and the memory occupied by the object is freed, theweakreference object is added to its referencequeue (if the latter exists).

D, The GC discovers an object memory with only a virtual reference, then:

the heap object referenced by ①phantomreference is declared as finalizable.

②phantomreference is added to its referencequeue before the heap object is freed .

Notable places include the following:

1,GC in general will not find soft-referenced memory objects, only when the memory is clearly insufficient to discover and release the soft reference object memory.

2, theGC Discovery and release of weak references is not immediately, sometimes need to repeat several times GC, only to find and release the weak reference memory objects.
3, soft reference and weak reference when added to referencequeue , its reference to the real memory has been set to empty, the associated memory has been released.

While the virtual reference is added to the Referencequeue, the memory is not released and can still be accessed.

Understanding and solving of Java memory leaks

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.