Talk about memory leaks in Java programming

  • 2020-04-01 04:16:50
  • OfStack

You have to know it first
1. C /c++ is the programmer's own memory management, Java memory is automatically collected by the GC.
I'm not familiar with C++, but I don't think I made a common sense mistake.
2. What is a memory leak ?
Memory leak refers to the existence of unrecoverable memory in the system, sometimes resulting in insufficient memory or system crash.
A memory leak occurs when memory is allocated in C/C++ without being freed.
3. Java has a memory leak
We have to admit this before we can move on. Although Java has memory leaks, you don't have to care much about them, especially if you don't care much about the code itself.
Memory leaks in Java are, of course, objects that are not useful but that the garbage collector cannot recycle.
And even if there are memory leaks, they don't necessarily show up.
4. In Java, parameters are passed.
There is basically no problem with primitive types, but there is no problem with reference types.
 

Java memory leaks
 
1. OutOfMemoryError: Java heap space
            In the JVM specification, the memory in the heap is used to generate object instances and arrays.
            If subdivided, the heap can also be divided into younger and older generations, which include one Eden zone and two survivor zones.
            When a new object is generated, the memory application process is as follows:
                  A. The JVM first tries to allocate the memory needed for the new object in Eden;
                  B. If the memory size is enough, the application ends, otherwise the next step;
                  C. The JVM starts youngGC and tries to release the inactive objects in Eden zone. If the Eden space is still insufficient to put the new objects after the release, it tries to put some active objects in Eden zone in Survivor zone.
                  D, Survivor is used as an intermediate swap zone between Eden and old. When there is enough space in the old zone, the objects of the Survivor zone will be moved to the old zone.
                  E. When the space of the OLD area is insufficient, the JVM will conduct full GC in the OLD area;
                  F, after full GC, "out of memory error" occurs if some of the objects copied from Eden are still unable to be stored in the Survivor and OLD areas, resulting in the JVM being unable to create a memory area for the new object in the Eden area:
                                                                 


 outOfMemoryError : java heap space

2. OutOfMemoryError: permgem space
            In the JVM specification, the method area mainly contains class information, constants, static variables, and so on.
            Therefore, if the program loads too many classes, or USES reflection, gclib and other techniques of dynamic proxy class generation, memory overflow may occur in this area. Generally, the error message when memory overflow occurs in this area is:


       outOfMemoryError : permgem space

3, thread stack overflow (Java. Lang. StackOverflowError)
            The thread stack is a memory structure that is unique to a thread, so the problem with the thread stack must be an error that occurred while a thread was running.
            Thread stack overflows are typically caused by too much recursion or too many levels of method invocation.
            The error message of stack overflow is:


       java . lang . StackOverflowError

Several scenarios for memory leaks:
 
1. Long-lived objects hold references to short-lived objects
 
                      This is the most common scenario for memory leaks and a common problem in code design.
                      For example, local variables are cached in a global static map with no cleanup operations. Over time, the map grows larger and larger, causing memory leaks.
 
2. Modify the parameter value of the object in the hashset, and the parameter is the field to calculate the hash value
 
                        When an object is stored into the HashSet collection later, can't modify the object of those involved in the calculation of the hash value fields, otherwise the hash value of the modified object with initial storage into HashSet set the hash value is different, in this case, even in the contains method is used as the object of the current reference to retrieve objects from the set HashSet, will also return to find the result of the object, which will lead to can't delete the objects from the collection HashSet, cause memory leaks.
 
3. Set the connection number and closing time of the machine
 
                      Memory leaks can also occur when very expensive connections are left open for long periods of time.


 
Here's an example of a memory leak:


public class Stack {
 private Object[] elements=new Object[10];
 private int size = 0;
 
 public void push(Object e){
 ensureCapacity();
 elements[size++] = e; 
 }
 
 public Object pop(){
 if( size == 0) 
  throw new EmptyStackException(); 
 return elements[--size];
 }
 
 private void ensureCapacity(){
 if(elements . length == size){
  Object[] oldElements = elements;
  elements = new Object[2 * elements . length+1];
  System . arraycopy(oldElements,0, elements, 0, size);
 }
 }
}

The above principle should be very simple, if the stack adds 10 elements, and then all of them pop out, although the stack
It's empty, there's nothing we want, but it's an object that can't be recycled, and that's what makes it in memory
Two conditions of leakage: useless and unrecoverable.
 

But even the existence of such things does not necessarily lead to any consequences, if the stack is used less,
I'm just wasting a few K's of memory, because we've got G's of memory, so what's the impact
This thing will be recycled soon. What does it matter? Let's look at two examples.
 
Example 1


public class Bad{
  public static Stack s=Stack();
  static{
    s . push(new Object());
    s . pop(); //There is an object with a memory leak
    s . push(new Object()); //The above object can be recycled, which is self-healing
  }
}


Because it's static, it's there until it exits, but we can also see that it's self-healing,
That means that if your Stack has at most 100 objects, there are at most 100 objects that can't be recycled
It should be easy to understand that the Stack holds 100 references internally, and at worst they all are
Useless, because once we put in the new enterprising, the previous quote will disappear naturally!
 
Example 2


public class NotTooBad{
  public void doSomething(){
    Stack s=new Stack();
    s . push(new Object());
    //other code
    s . pop();//This also results in uncollectible objects and memory leaks.
  }//Exit method,s automatically invalid,s can be recycled, the reference inside the Stack naturally disappeared, so
   //You can also self-heal here, and you can say that there is no memory leak problem with this method, just a little later
   //I'm just going to give it to the GC, because it's closed and it's not open to the public, so I can say code 99 above. 9999% of the
   //The situation doesn't make any difference, and of course you can write code like this without any bad effects, but
   //Absolutely garbage code! There's no contradiction. I'm not going to have an empty for loop
   //What's too big an impact? Would you do that?
}

 
Both of the above examples are minor incidents, but memory leaks in C/C++ are not Bad, but Worst.
If they do not recycle a place will never be recycled, frequent calls to this method memory is not used up!
Because Java also has a self-healing feature (my own name, not yet patented), Java has a memory leak problem
Can ignore almost, but know the person did not make.

To avoid memory leaks, here are some Suggestions for writing code:
 
1. Release references to useless objects as soon as possible;
 
2, use String processing, avoid using String, should use a lot of StringBuffer, each String object has to occupy a separate area of memory;
 
3. Use static variables as little as possible, because static variables are stored in the permanent generation (method area), and the permanent generation basically does not participate in garbage collection;
 
4. Avoid creating objects in a loop;
 
5. It is easy to run out of memory to open a large file or take too much data from the database at once, so it is necessary to roughly calculate the maximum amount of data in these places, and set the required minimum and maximum value of memory space.


Related articles: