Talking about and summarizing Java memory leaks

Source: Internet
Author: User

I. Definition

First of all, what is memory leak, simple point is used up forget to recycle, and other objects and other resources want to use but can not use a "stand manger not to poop" waste of resources situation. In C + +, the most leaking scenario is when a program leaves a running domain, such as a new object in a method body or a struct of malloc, and only if the local variable in the method body points to the memory area, when the method returns, there is a local variable pointer in the stack that is destroyed with the stack frame. , then there is no pointer to the memory area, then this area of memory is leaking.

And what about Java's memory leaks? As is known to all, Java's memory recycling is managed by the GC. The GC runs the accessibility algorithm, and the GC thread in the JVM starts the Java object from a specific object gcroot, as a tree, traversing the tree to determine the accessibility of the object, and the static pointer count of C + + having an essential difference, without the confusion of the mutual references between useless objects. This means that Java objects may be recycled when the Java object really does not have a (strong) reference (except for weak references). In other words, the Java memory leaks here are not the same as the traditional C + + .

is the accessibility algorithm for Java:

two. What is a memory leak in Javaa personal understanding of a Java memory leak can be described as: an object is forgotten or a reference is not found. Because in Java, if the object is still alive in the heap (except before the death GC is recycled), then there is bound to be a reference to the object throughout the environment, in short, "This person is alive and there must be a meaning for its existence". so the question is, where is the quote? We developers can't see in the code? Don't worry, this is the key to the Java memory leak. many times these unseen references are hidden in a frame, in a static variable, or in a sub-thread that is still running .... Here are a few examples that you might understand. three. Common Scenarios1.HashMap, sometimes, we accidentally put variable Hashcode object as HashMap key, when you accidentally changed the hashcode of the object, key can not take out the corresponding value, This value cannot be reached for you. However, the reference to value is still present in the array and linked list structures inside the HASHMAP framework. And you have no alternative, the memory will "leak". A common context leak (activity representative) in 2.Android. In Android, the context object reference should be handled with care, because the Android Application Layer framework helps us manage the life cycle of the activity (context) object, which can almost represent the IOC framework that we now commonly use, the birth and death of the framework management object, Developers only have the right to apply. If you accidentally plug a Context object into a static variable, or refer to which long-period strand approached, etc., at the end of the activity, the frame layer runs through all the destruction programs, removing its reference to the context, At this point the framework thinks the context is dead. The framework did not think that there were other references outside of him that were not released. This creates a leak. 3. Static variables, this does not have too much elaboration, very good understanding. 4. Resource objects are not freed, such as databases, to stream these resource classes, such as Cusor,file.socket. The reason is that because these interfaces that interact with the local platform involve JNI, there may be pointers to the native layer referencing the Java Layer object, and the reference is always present without releasing it. 5non-static internal classes, especially handler and runnable within the activity, are associated with the previous elaboration. The non-static inner class contains a strong reference to the external category, and this reference is added by the compiler itself, the developer is invisible in the source code, so it is more covert. If you decompile an internal class in activity you will find:
# instance Fields.field final synthetic this$0:lcom/gy/just/voltagemonitor/view/activity/yunweiactivity;. Field final synthetic val$sec:i# Direct Methods.method constructor <init> (lcom/gy/just/voltagemonitor/view/ Activity/yunweiactivity;i) v.    locals 0    . param p1, "this$0"    # lcom/gy/just/voltagemonitor/view/activity/ yunweiactivity;
The compiler automatically adds an external class variable called "this$0" to the inner class, and assigns a value to the constructor. Then the inner class holds an invisible external class strong reference. Internal classes such as Runnable,handler, such as the fruit thread, do not end, so the leakage of the outer class object is easy to happen.So, let's do an interesting little experiment, what would happen if we empty the reference to the inner class?
public class B extends a{public void Test () {new ' Thread ' (New Demo ()). Start (); @Overridepublic void Dosth () {//TODO auto-generated method StubSystem.out.println ("DoB");} Class Demo implements Runnable{public demo () {try {Field field = GetClass (). Getdeclaredfield ("this$0"); Field.setaccessible (True); Field.set (this, null);} catch (Nosuchfieldexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (SecurityException e) {//To Do auto-generated catch Blocke.printstacktrace ();} catch (IllegalArgumentException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch ( Illegalaccessexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} @Overridepublic void Run () {//TODO auto-generated method Stubdosth ();}}}
The run exception is as follows
Public abstract interface Java.util.list<e>exception in thread "Thread-0" Java.lang.NullPointerExceptionat test. B$demo.run (b.java:46) at Java.lang.Thread.run (thread.java:745)

What do you think? The Inner class demo has been unable to invoke the Dosth method of the outer class, throwing a null pointer exception.
Four. Summary, strictly speaking Java is no real memory leaks, these leaks and we can not see the framework of the internal closely related, so develop good programming habits, understand the structure of the common framework of the principle of understanding, will be able to avoid these errors. Finally, if you think the younger brother understand is also good, may give a praise, Tao friends feel that there are errors in understanding is also welcome to correct, after all, this is my personal view.


Talking about and summarizing 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.