"Effective Java Chinese version 2nd edition" study note 6th: Eliminate outdated object references

Source: Internet
Author: User

  The first common source of a memory leak is the existence of an expired reference.

1 Importjava.util.Arrays;2 Importjava.util.EmptyStackException;3 4  Public classStack {5     6     Privateobject[] elements;7     Private intSize = 0;8     Private Static Final intDefault_initial_capacity = 16;9     Ten      PublicStack () { Oneelements =Newobject[default_initial_capacity]; A     } -      -     Private voidensurecapacity () { the         if(Elements.length = =size) { -elements = arrays.copyof (elements, 2 * size + 1); -         } -     } +      -      Public voidpush (Object e) { + ensurecapacity (); Aelements[size++] =e; at     } -      -      PublicObject Pop () { -         if(Size = = 0) { -         Throw Newemptystackexception (); -     } in          -         returnelements[--size]; to     } +      -}

  If a stack grows first and then shrinks, the objects that are popped from the stack are not garbage collected, and they are not recycled even if the program using the stack no longer references those objects. Because the stack internally maintains an outdated reference to these objects (obsolete reference). An expired reference is a reference that will never be lifted again. In this case, any references outside the active section (active portion) of the elements array are out of date. The active part refers to those elements in the elements that are smaller than size.

If an object reference is unconsciously persisted, the garbage collection mechanism not only reclaims the object, but does not reclaim all other objects referenced by the object. Workaround: Once the object reference has expired, simply clear the references. In this case, whenever an element is ejected from the stack, the reference to it expires. Modify the following:

1  PublicObject Pop () {2     if(Size = = 0) {3     Throw Newemptystackexception ();4     }5         6Object result = elements[--size];7Elements[size] =NULL;//Clear References8         9     returnresult;Ten}

Another benefit of emptying expired references is that if they are later incorrectly dereferenced, the program throws the NullPointerException exception immediately, rather than silently running it in a wrong way. It is always helpful to detect errors in the program as quickly as possible. The best way to eliminate an expired reference is to have the variable that contains the reference end its life cycle. If you define each variable within the most compact scope (see 45th), this happens naturally.

As long as the class is managing memory itself, programmers should be wary of memory leaks. Once the element is freed, any object references contained in the element should be emptied.

A second common source of memory leaks is caching.

By putting an object reference in the cache, it is easily forgotten, leaving it in the cache for a long time after it is no longer useful. When you use Weakhashmap to represent the cache, when items in the cache expire, they are automatically deleted. Weakhashmap only works if the life cycle of the cache entry is determined by the external reference of the key and not by the value.

As time goes by, the cache entries become less valuable, and the cache should clear out useless items at times. Can be done by a background thread (possibly a timer or scheduledthreadpoolexecutor), or cleaned up when a new entry is added to the cache. The Linkedhashmap class can implement the latter through its Removeeldestentry method. For more complex caches, you must use Java.lang.ref directly.

A third common source of memory leaks is listeners and other callbacks.

If the client registers callbacks in its own implementation of the API, but does not explicitly unregister, they will accumulate unless some action is taken. The best way to ensure that callbacks are immediately treated as garbage collection is to save only their weak references (weak reference), for example, to save them only as keys in Weakhashmap.

Memory leaks can often be discovered only by carefully examining the code, or by using the heap profiler.

Resources

"Effective Java Chinese version 2nd edition" p21-23

Effective Java Chinese version 2nd edition of the study note 6th: Eliminate outdated object references

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.