Java Memory leakage understanding and Solution

Source: Internet
Author: User

For more information, see blogjava.net/zh-weir/archive/2011/02/23/345007.html.

Java Memory Management Mechanism


In C ++, if a piece of memory needs to be dynamically allocated, the programmer must be responsible for the entire lifecycle of the memory. From application distribution, to use, to final release. This process is flexible, but cumbersome. It is easy for programmers to forget to release the memory due to negligence, resulting in Memory leakage. The Java language optimizes memory management. This is the garbage collection mechanism. Almost all memory objects in Java are allocated on the heap memory (except for basic data types), and GC (garbage collection) is responsible for Automatic Recovery of memory that is no longer in use.

The above is the basic situation of the Java memory management mechanism. However, if we only understand this, we will still encounter Memory leakage in actual project development. Some people may doubt that since Java's garbage collection mechanism can automatically recycle memory, how can there be Memory leakage? In this case, we need to know when GC recycles memory objects and what memory objects will be considered "no longer used" by GC.

The access to memory objects in Java is referenced. In Java code, we maintain a reference variable for a memory object. With this reference variable value, we can access the memory object space in the corresponding memory address. In Java programs, the referenced variable can store both heap memory and code stack memory (the same as the basic data type ). The GC thread starts tracing from the referenced variable in the Code stack to determine which memory is in use. If the GC thread cannot track a heap memory in this way, GC considers that the memory will no longer be used (because the memory cannot be accessed in the Code ).

With this directed graph memory management method, GC can recycle a memory object after all references are lost. Conversely, if this object still has references, it will not be recycled by GC, even if the Java Virtual Machine throws an OutOfMemoryError.

 

Java Memory leakage


Generally, there are two scenarios for Memory leakage. For example, in C/C ++, the memory allocated in the heap is not released, all the methods that can access this memory are deleted (for example, the pointer is assigned a value again); the other is when the memory object is clearly not needed, the memory and its access method (reference) are still retained ). In the first case, the garbage collection mechanism has been introduced in Java, which has been well solved. Therefore, the memory leakage in Java mainly refers to the second case.

The concept may be too abstract. You can take a look at this example:

 

1 Vector v = new Vector (10 );
2 for (int I = 1; I <100; I ++ ){
3 Object o = new Object ();
4 v. add (o );
5 o = null;
6}

In this example, the reference v of the Vector Object and the reference o of the Object exist in the Code stack. In the For loop, we constantly generate new objects, add them to the Vector object, and then leave the o reference empty. The problem is, if GC occurs after the o reference is left empty, can the Object we created be recycled by GC? The answer is no. Because, when GC traces the reference in the Code stack, it will find the v reference, and continue to trace down, it will find that there is a reference pointing to the Object in the memory space that the v reference points. That is to say, although the o reference has been left empty, other references still exist in the Object, which can be accessed, so GC cannot release it. If the Object has no effect on the program after this loop, we think the Java program has a memory leakage.

Despite the memory leakage in C/C ++, Java Memory leakage causes little damage, except for a few cases where the program crashes, in most cases, the program can still run normally. However, when mobile devices have strict restrictions on memory and CPU, Java memory overflow may lead to low program efficiency and a large amount of unnecessary memory. This will cause the performance of the entire machine to deteriorate. In severe cases, it will also throw an OutOfMemoryError and cause the program to crash.

 

Generally, memory leakage is avoided.


In general, Java Memory leakage does not involve complex data structures. the lifecycle of a memory object exceeds the length of time required by the program. We sometimes call it "object free ".

For example:

 

1 public class FileSearch {
2
3 private byte [] content;
4 private File mFile;
5
6 public FileSearch (File file ){
7 mFile = file;
8}
9
10 public boolean hasString (String str ){
11 int size = getFileSize (mFile );
12 content = new byte [size];
13 loadFile (mFile, content );
14
15 String s = new String (content );
16 return s. contains (str );
17}
18}

In this Code, the FileSearch class has a function hasString to determine whether the document contains a specified string. The process is to first load the mFile into the memory and then judge. However, the problem here is that the content is declared as an instance variable rather than a local variable. Therefore, after this function is returned, the data of the entire file still exists in the memory. Obviously, we do not need this data in the future, which leads to a waste of memory for no reason.

To avoid Memory leakage in this case, we need to manage our allocated memory with C/C ++ memory management thinking. First, define the effective scope of the memory object before declaring the object reference. A valid memory object in a function should be declared as a local variable, and the same as the class instance life cycle should be declared as an instance variable ...... And so on. Second, remember to manually leave the reference blank when the memory object is no longer needed.

 

Memory leakage in complex data structures


In actual projects, we often use some complicated data structures to cache the data information required during the program running. Sometimes, because the data structure is too complex, or we have some special requirements (for example, if the memory permits, as much cache information as possible to increase the program running speed ), it is difficult to clearly define the data lifecycle in the data structure. At this time, we can use a special mechanism in Java to prevent memory leakage.

We have previously introduced that the GC mechanism of Java is based on the reference mechanism of the trace memory. Before that, all the references we used were defined in the form of "Object o. In fact, this is only a default situation in the Java reference mechanism. In addition, there are some other reference methods. By using these special reference mechanisms and GC mechanisms, we can achieve some of the results we need.

 

Several references in Java


Java has several different reference methods: strong reference, soft reference, weak reference, and virtual reference. Next, we will first have a detailed understanding of the significance of these reference methods.



Strong reference

The references we introduced earlier are strongly referenced, which is the most common reference. If an object has a strong reference, it is similar to an essential necessities. The Garbage Collector will never recycle it. When the memory space is insufficient, the Java Virtual Machine would rather throw an OutOfMemoryError to terminate the program abnormally and does not recycle strongly referenced objects to solve the problem of insufficient memory.

 

SoftReference)

SoftReference is typically used for memory-sensitive high-speed caching. SoftReference is used to ensure that all soft references are cleared before the JVM reports insufficient memory when the object is referenced. The key is that the Garbage Collector may (or may not) release software and objects at runtime. Whether the object is released depends on the garbage collector algorithm and the amount of memory available when the garbage collector is running.

 

WeakReference)

A typical use of the WeakReference class is canonicalized mapping ). In addition, for objects with relatively long lifetime and Low Re-creation overhead, weak references are also useful. The key is that if the spam collector encounters a weak object during runtime, The WeakReference reference object will be released. However, note that the spam Collector may have to run multiple times to locate and release weak accessible objects.

 

PhantomReference)

The PhantomReference class can only be used to track the forthcoming collection of referenced objects. It can also be used for pre-mortem cleanup. 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, the PhantomReference object is placed on its ReferenceQueue. Placing the PhantomReference object in the ReferenceQueue is also a notification, indicating that the object referenced by the PhantomReference object has ended and can be collected. This allows you to take action just before the memory occupied by the object is recycled. Reference and ReferenceQueue.

 

Interaction between GC, Reference, and ReferenceQueue


A. GC cannot delete the memory of strongly referenced objects.

 

B. GC finds a soft-referenced object memory, so:

① The referent field of the SoftReference object is set to null, so that the object does not reference 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 released

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.