Sixth: Elimination of expired object references

Source: Internet
Author: User

The Java garbage collection mechanism does not mean that we do not need to consider memory management issues.

Consider:

 Public classStack {pprivateobject[] elements; Private intSize =0; Private StaticFinalintDefault_inital_capacity = -;  PublicStack () {Elements=NewObject[default_inital_capacity]; }         Public voidpush (Object e) {ensurecapacity (); Elements[size++] =e; }         PublicObject Pop () {if(Size = =0) {            Throw Newemptystackexception (); }        returnElements[--size]; }        Private voidensurecapacity () {if(Elements.length = =size) Elements= arrays.copyof (Elements,2* Size +1); }}

This is a stack of your own writing.

This program does not have any obvious errors, but this program hides a problem with memory leaks.

If a stack grows first and then shrinks, then the objects that are popped from the stack are not garbage collected because the references to these outdated objects are still maintained inside the stack, and the so-called expiration reference refers to those elements in the elements that are greater than or equal to size (because the stack grows shrinking, So it is entirely possible that if an object is left unconscious (that we do not want), then the other objects referenced by the reference will not be recycled by the garbage collection mechanism because there are still references, and the GC thinks the objects will still be used. As programs run longer, outdated object references consume more memory and cause program performance to degrade.

The workaround for this type of problem is that once the object reference has expired, simply clear the references.

 Public Object Pop () {        if(size = = 0)            {thrownew  emptystackexception ();        }         = elements[--size];         NULL ;//explicitly empty the reference         return result;}

Emptying an object reference should be an exception, not a canonical behavior, and does not require or advise programmers to refer to each object, and once the program is no longer used, it can be emptied, which often makes the code confusing.

The best way to eliminate out-of-date references is to define each variable in the most compact scope, and when the scope is executed, the GC automatically reclaims the variables that expire the scope.

When should you empty the reference yourself?

In general, you should be wary of memory leaks as long as you are managing memory yourself. If you open up a memory space and hold a reference to that space all the time, it is your responsibility to manage it because the GC cannot automatically recycle the memory that you commit to manage unless you tell it (explicitly empty the reference).

In the JDK, there is already a stack class ready for us to use to see how it implements Pop:

 Public synchronizede pop () {e obj; intLen =size (); Obj=peek ();//This method takes the top element out of the stack, but does not eject the top element of the stack removeelementat (Len-1);//This is the method of the stack parent class that pops the top element of the stack        returnobj;} Public synchronized voidRemoveelementat (intindex) {Modcount++; if(Index >=Elementcount) {            Throw NewArrayIndexOutOfBoundsException (index + ">=" +elementcount); }        Else if(Index < 0) {            Throw Newarrayindexoutofboundsexception (index); }        intj = Elementcount-index-1; if(J > 0) {system.arraycopy (elementdata, index+ 1, Elementdata, Index, J); } Elementcount--; Elementdata[elementcount]=NULL;/*To-let GC do it work*//can see that the implementation of the JDK is explicitly emptying the reference to tell the GC to recycle the expired reference}

Memory leaks typically do not manifest as significant failures that can exist in the system for many years, only by examining the code, or by using the heap Profiler tool to discover a memory leak issue. So try to know how to predict such problems before a memory leak occurs.

Sixth: Elimination of expired object references

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.