Is there a memory leak in Java?

Source: Internet
Author: User

The so-called memory leak refers to an object or variable that is not being used by the program has been occupied in memory. There is a garbage collection mechanism in Java that ensures that an object is no longer referenced when the object is programmed to orphan, and the object is automatically erased from memory by the garbage collector. Because Java uses a graph-like approach to garbage collection management, you can eliminate the problem of reference loops, such as having two objects and referencing each other, so that GC can reclaim them as long as they and the root process are unreachable, such as the following code can see the memory reclamation of this situation:

 PackageCom.huawei.interview;Importjava.io.IOException; Public classGarbagetest {/**     * @paramargs *@throwsIOException*/     Public Static voidMain (string[] args)throwsIOException {//TODO auto-generated Method Stub       Try{gctest (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.println ("Has exited gctest!");       System.in.read ();          System.in.read (); System.out.println ("Out Begin gc!");  for(inti=0;i<100;i++) {System.GC ();           System.in.read ();       System.in.read (); }    }     Private Static voidGctest ()throwsIOException {System.in.read ();          System.in.read (); Person P1=NewPerson ();       System.in.read ();          System.in.read (); Person P2=NewPerson ();       P1.setmate (p2);       P2.setmate (p1); System.out.println ("Before Exit gctest!");       System.in.read ();          System.in.read ();       System.GC (); System.out.println ("Exit gctest!"); }     Private Static classPerson {byte[] data =New byte[20000000]; Person Mate=NULL;  Public voidsetmate (person other) {mate=Other ; }    }}

Memory leaks in Java: Long life-cycle objects that hold references to short life-cycle objects are likely to have a memory leak, even though short life-cycle objects are no longer needed, but because long-life-cycle objects hold their references and cannot be recycled, this is where memory leaks occur in Java, in layman's words, Is that the programmer might have created an object that would never be used in the future, and this object has been referenced, that is, the object is useless but cannot be reclaimed by the garbage collector, which is a possible memory leak in Java, for example, the cache system, we loaded an object in the cache ( For example, in a global map object), and then no longer using it, the object has been cached for reference, but is no longer used.

Check for memory leaks in Java, be sure to let the program complete the various branches of the program to the end, and then see if an object has been used, if not, you can determine that the object is a memory leak .

If the method of an instance object of an external class returns an instance object of an inner class, the inner class object is referenced for a long time, even if the Outer class instance object is no longer being used, but because the inner class persists the external class's instance object, the Outer class object will not be garbage collected, which will also cause a memory leak.

The following is from the Internet (the main feature is to empty the stack of an element, not to completely remove it from the array, but to reduce the total number of storage, I can write better than this, when taking off an element, by the way also let it disappear from the array, the location of the element where the value is set to NULL):

I can not think of a more classic example than that stack, so that I have to cite other people's example, the following example is not what I think of, is the book, of course, if not seen in the book, it may be some time I want to, but then I said that I think of no one believed.

 Public classStack {PrivateObject[] Elements=NewObject[10]; Private intSize = 0;  Public voidpush (Object e) {ensurecapacity (); Elements[size++] =e; }     PublicObject Pop () {if(Size = = 0)    Throw Newemptystackexception (); returnelements[--size]; }    Private voidensurecapacity () {if(Elements.length = =size) {object[] oldelements=elements; Elements=NewObject[2 * elements.length+1]; System.arraycopy (Oldelements,0, elements, 0, size); }    }    }

the above principle should be very simple, if the stack added 10 elements, and then all pop out, although the stack is empty, there is nothing we want, but this is an object can not be recycled, this is in line with the memory leakage of the two conditions: useless, can not be recycled.

But there is such a thing does not necessarily lead to what kind of consequences, if the stack with less, also wasted a few k memory, anyway, our memory is on G, where there will be any impact, say this thing will soon be recycled, what is the relationship. Let's look at two examples below.

Example 1

 Public class bad{    publicstatic stack s=stack ();     Static {    s.push (new  Object ());     // There's a memory leak    in an object here. S.push (new// Upper object can be recycled, is equivalent to self-healing     }    }


because it is static, it always exists until the program exits, but we can also see that it has a self-healing function, that is, if your stack has a maximum of 100 objects, then only 100 objects can not be recycled in fact, this should be easy to understand, the stack holds 100 references inside, The worst case scenario is that they are useless, because once we put in a new enterprising, the previous reference disappears naturally!

Another case of memory leaks: When an object is stored in the HashSet collection, it is not possible to modify the fields in the object that participate in the hash value, otherwise the hash value of the modified object is different from the one originally stored in the HashSet collection, in which case Even if the Contains method uses the object's current reference as a parameter to retrieve the object in the HashSet collection, the result of the object cannot be found, which also results in a memory leak that prevents the current object from being deleted separately from the HashSet collection.

Is there a memory leak in Java?

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.