Java memory leaks-full parsing and processing methods [reprint]

Source: Internet
Author: User

Java memory leak-full parsing and processing methods [reprint]@author Small Basket@address http://www.jianshu.com/p/bf159a9c391a

This article explores the issue of memory leaks step-by-step.
Bo Master for the first time to write long technical stickers, if there are errors or not thoughtful place please advise.

Java is a garbage-collected language, and developers don't have to deliberately manage memory allocations. However, there is still a lot of memory leaks in Java, if you do not handle the memory leaks, will cause the app memory unit can not be freed and wasted, eventually causing memory to occupy the stack (heap) explosion and then the program crashes .

Memory leaks

When it comes to memory leaks , we have to mention memory overruns , two more confusing concepts that we can analyze.

    • Memory leak : The program is not freed after it has been used after it has been applied to the system to allocate memory space (new). The result is that the memory unit is always occupied, and neither we nor the program can use the memory unit until the end of the program, which is a memory leak.

    • Memory Overflow : The program has requested more memory space than the system can give. For example, memory can only be assigned an int type, but I fortress give him a long type, the system will appear oom. Another example is a car can sit up to 5 people, but you are not a fortress under 10, the car is bursting.

A large amount of memory leaks can cause a memory overflow (oom).

Memory

To understand memory leaks, it is essential to understand memory.
Java is run in the virtual memory environment of the JVM, and the JVM's memory can be divided into three extents: heap, stack (stack), and method area.

    • Stack: is a simple data structure, but is widely used in computers. The most notable features of the stack are:LIFO (last in, first out, LIFO). For example, we put clothes in the box, first put in the bottom, only to take out later put in to get the clothes below. Only the base type and object references (not objects) are stored in the stack.

    • heap: heap memory is used to store objects and arrays created by new . The memory allocated in the heap is managed by the Java Virtual Machine automatic garbage collector. Only one heap of JVM (heap) is shared by all threads, and the heap does not hold basic types and object references, only the object itself.

    • method Area: Also called the static zone, like the heap, is shared by all threads. The method area contains all class and static variables.

After the memory concept is probably understood, the question to consider is:
Where exactly is the memory that will let us cause a memory leak?

All right, now that the Black brothers are asking questions, let's continue with the chatter!

Memory leak cause Analysis

In Java, the stack of the JVM records the invocation of the method, with each thread owning a stack. As the thread runs, it executes to a new method call, adding a memory unit, the frame, to the stack. In a frame, the parameters, local variables, and return addresses of the method call are saved. However, a local variable in Java can only be a primitive type variable (int), or a reference to an object. Therefore, only the base type variables and object references are stored in the stack. the referenced object is saved in the heap.

When a method runs at the end, the corresponding frame of the method is removed from the stack, and the space occupied by all local variables and parameters in the frame is freed. The thread goes back to the original method and executes, and when all the stacks are emptied, the program runs to the end.

For heap memory, the heap stores common variables. In Java, heap memory is not emptied with the end of the method, so local variables are defined in the method, and the variables remain in the heap after the method ends.

In summary, stacks can clean up unused memory space on their own. But if we keep creating new objects, the heap's memory space will be exhausted. So Java introduced garbage collection (garbage collection, referred to as GC) to deal with heap memory recycling, but if the object has been referenced can not be recycled, resulting in a waste of memory, can no longer be used. So objects can not be recycled by GC is the cause of memory leaks!

Garbage collection mechanism

Garbage collection (garbage collection, referred to as GC) automatically empties objects that are no longer used in the heap. In Java, objects are used by reference. If no reference is directed to the object, the object is not processed or called, and the object is called unreachable (unreachable). garbage collection is used to free up memory occupied by unreachable objects.

Realization idea: We define the stack as root, traverse the references of all the objects in the stack, and then traverse through the objects in the heap. Because the references to the objects in the stack are deleted, we can find objects that are not pointed to in the heap by reference to the objects in the stack, which are not reachable objects and are garbage collected.


Idea of garbage collection realization

If you hold a strong reference to an object, the garbage collector is unable to reclaim the object in memory.

Reference type

In previous versions of JDK 1.2, if an object was not referenced by any variable, the program could no longer use the object. That is, only the object is in the accessible (reachable) state before the program can use it. Starting with JDK version 1.2, the reference to the object is divided into 4 levels, giving the program more flexibility in controlling the object's life cycle. These 4 levels are high to low in order: Strong references, soft references, weak references, and virtual references.
Java/android reference types and their usage analysis

1. Strong references (strong reference)
One of the most common reference types in actual coding. Common forms such as: a A = new A (); The strong reference itself is stored in the stack memory, and its storage points to the address of the object in memory. In general, when a strong reference to an in-memory object no longer points to it, the garbage collection machine begins to consider a possible garbage collection of this memory. For example, when encoding: a = null, at this point, there is no other reference to the new a object that has just been assigned an address in the heap, and the heap memory is garbage collected when the system is garbage collected.

2. Soft reference (Soft Reference)
The general use form of soft references is as follows:

A = new A ();
softreference<a> SrA = new softreference<a> (A);

The following two conditions are required for garbage collection of objects indicated by soft references:
1. When its indicated object does not have any strong reference to the object pointing to it;
2. When the virtual machine is low on memory.
As a result, the SoftReference in disguise extends the time it indicates that the object occupies heap memory until the garbage collector reclaims this heap memory space until the virtual machine has insufficient memory.

3. Weak references (Weak Reference)
Similarly, the general use of soft references is as follows:

A = new A ();
weakreference<a> WrA = new weakreference<a> (A);

WeakReference does not change the garbage collection time of the original strongly referenced object, and once it indicates that the object does not have any strongly referenced objects, the object enters the normal garbage collection process.

4. Virtual references (Phantom Reference)
Compared with softreference or weakreference, the main differences of Phantomreference are as follows:
1.PhantomReference has only one constructor

Phantomreference (T referent, referencequeue<? super T> Q)

2. Whether or not a strong reference is directed to the Phantomreference object, the Phantomreference Get () method returns the result null.

Therefore, the use of phantomreference must be combined with referencequeue;
As with WeakReference, Phantomreference does not change the garbage collection timing of its indicated objects.

Memory Leak Reason

If you hold a strong reference to an object, the garbage collector is unable to reclaim the object in memory.

The true cause of memory leak is: holding the object's strong reference, and not released in time, resulting in the memory unit has been occupied, wasted space, may even cause memory overflow!

In fact, there are two different scenarios in which memory leaks can occur in Android:
    • The static variable of the global process (Process-global). This ignores the state of the application and holds the activity's strong reference to the monster.
    • Threads that live outside the activity life cycle. A strong reference to the activity was not emptied.

Check your project for the following scenarios:

    • Static Activities
    • Static views
    • Inner Classes
    • Anonymous Classes
    • Handler
    • Threads
    • TimerTask
    • Sensor Manager

See the article "Eight possibilities for Android memory leaks"

Finally, we recommend a program that detects app memory leaks: leakcanary (can detect memory leaks in your app)

Summarize

Although mobile phone memory is constantly improving, memory leaks may not be like the Dalvik era due to the virtual machine memory too small cause a variety of oom. However, excessive memory leaks will still cause memory overflow, affect the user experience, in today's custom system, more and more models to solve the problem of memory leaks will make the adaptation and stability to further improve!

I hope my article will bring you a little bit of welfare, that is happy enough in the next.
See you next time!

Java memory leaks-full parsing and processing methods [reprint]

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.