Java-Memory leakage

Source: Internet
Author: User
Java's garbage collection mechanism makes many Programmers think that memory management is not very important, but memory leakage occurs due to such negligence. Especially for Android development, memory management is more important, good habits help avoid Memory leakage. Object status:Many objects and references can be viewed as directed graphs, vertices can be objects or references, and reference relationships are directed edges.
  1. Reachable state: when an object is created, a reference points to it. At this time, a reference relationship is established between the object and the reference, that is, the reference transmits a directed edge to the object, this object is out of the reachable state.
  2. Recoverable state: when the reference does not point to an object, the object is in recoverable State. At this time, the Finalize method will be called before the system recycles the object for resource cleaning, if the referenced variable can be referenced again after this method is called, the variable is restored to the reachable state. Otherwise, the variable changes to the inaccessibility state.
  3. Inaccessible state: when the object and the referenced variable lose the reference relationship and the Finalize method is called, the object cannot be restored to the reachable state, and the reference will be permanently lost, in this case, the system will actually recycle the memory occupied by the object.
What is memory leakage:Memory leakage means that the program is running. the Java garbage collection mechanism recycles some unsuitable memory and re-allocates it to ensure that the system can use the memory again, in Java, all the inaccessibility states will be recycled, but some objects that are in the reachable state, but are no longer used by the Program (occupying the trap), these memories cannot be recycled, they are useless for programmers, but they are reachable for the garbage collection mechanism, so they are "useful" for Memory leakage. Example of a stack:
Package crazyjava; import javax. management. runtimeerrorexception;/*** @ author CCF ***/public class neicun {/*** @ Param ARGs */class Stack {private object [] elementdata; private int size; private int capacityincrement; Public stack (INT initialcapacity) {elementdata = new object [initialcapacity];} public stack (INT initialcapacity, int capacityincrement) {elementdata = new object [initialcapac Ity]; this. capacityincrement = capacityincrement;} public void push (Object object) {ensurecapacity (); elementdata [size ++] = object; // Postfix} public object POP () {If (size = 0) throw new runtimeexception ("Empty stack exception"); object ele = elementdata [-- size]; // This is a local variable. When the method ends, the partial variable elementdata [size] = NULL is recycled; // The strong reference relationship is eliminated to avoid internal leakage. Return ele; // return the size of the top element of the stack minus 1 Length} public int size () {return size;} private void ensurecapacity () {// todo auto-generated method stub // The array is full.. If (elementdata. length = size) {object [] oldelmentata = elementdata; int newlength = 0; If (capacityincrement> 0) {newlength = elementdata. length + capacityincrement;} else {newlength = (INT) (elementdata. length * 1.5);} elementdata = new object [newlength]; system. arraycopy (oldelmentata, 0, elementdata, 0, size) ;}} public static void main (string [] ARGs) {// todo auto-generated method stub stack = new neicun (). new stack (10); For (INT I = 0; I <10; I ++) {stack. push ("element" + I) ;}for (INT I = 0; I <10; I ++) {system. out. println (stack. pop ());}}}

  

In the code, the POP () function implements the stack, where elementdata [size] = NULL; Removes the reference relationship between the element and its reference, so that the element enters the inaccessibility state, it can be recycled by the system. If reference is not cut off, the element will remain reachable and will be resident in the memory. For the last object ele = elementdata [-- size];, this element is used as the return value. Some people may ask why this will not cause memory leakage, the object here is a local variable. The life cycle of the local variable is the same as that of the method. The method is over, local variables will be reclaimed by the garbage collection mechanism, so this worry is unnecessary. From the above point of view, memory leakage is very likely. Strong reference types (which will be discussed later in the blog) make us use the most useful types, this type of reference can be recycled only when the reference is lost. In other cases, it cannot be recycled. Therefore, a good programming habit is a good way to avoid Memory leakage.How to avoid Memory leakage:

    1. Try to use as much direct as possible
      For example, string type
      String A = "CCF" // uses a direct amount. The JVM string pool caches this string.
      String B = new string ("CCF"); // If the constructor is called directly, the CCF three characters are stored in the character array because the string is based on the array.
    2. Use stringbuilder and stringbuffer
      String operations using stringbuilder and stringbuffer can reduce the temporary strings produced by string operations.
    3. Release useless object references, just like the POP () method on the stack above
    4. Use less static variables. The Life Cycle of static variables is the same as that of the class. When the class is loaded to the class, it means that the program ends.
    5. Avoid creating objects in loops and frequently called methods, because a large number of objects are generated, especially for loops.
    6. Cache objects that are frequently used to avoid repeated creation of the same object. If you want to rewrite getview In the android adapter, the object cache technology is often used.

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.