2 small examples of [Java] memory leaks __java

Source: Internet
Author: User
Public Object pop () { 
if (size==0) throw new Emptystackexception (); 
return element[--size]; Transient memory leak 
} 

Each time the above code pops (), stack pops up an element, and there is actually a reference element[x to the object that has popped up before the new element is added, so the GC is not garbage collected. Only the push () of the new element makes the Element[x]=newobject, which makes the previously created object likely to be reclaimed. It is much safer to change the above pop () method to the following code:

Public Object pop () {  
       if (element.length==size) throws Emptystackexception ();  
       Object O=element[--size];  
       Elements[size]=null;  Gives GC a chance to recycle this object return   
       o;  
}  


B.getinstance (). SetA (this);

private static B Instance=new B (); 

public static B getinstance () { 


Obviously B uses singleton mode, he holds a reference to a object, and the object of Class A cannot be reclaimed. Imagine what happens if a is a larger object or a collection type.

Vector v = new vector (a);
for (int i = 1; i<100; i++)
{object o = new Object ();
V.add (o);
o = null;
}


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.