Can there be a memory leak in Java?

  1. Java uses garbage collection mechanism for memory management. In Java, objects are allocated memory (except basic data types) on the heap memory, and then the GC is responsible for automatically reclaiming the memory that is no longer used
  2. Access to memory objects in Java is done by reference. Reference variables are maintained in the code so that the memory object space can be accessed, and these reference variables are themselves stored on the stack. The GC thread will start tracking from the reference variable in the stack. If a certain heap memory cannot be tracked (unreachable), it is considered that this memory is no longer used.
  3. A memory leak in Java means that the memory object is no longer used, but its reference method and memory space are still preserved.

eg:

 

Vector v=new Vector(5);
for (int i=1;i<10; i++)
{
    Object o=new Object();
    v.add(o);
    o=null;  
}

 

We cyclically apply for the Object object and put the applied object into a Vector. If we only release the reference itself, the Vector still references the object, so this object is not recyclable for GC. Therefore, if the object must be deleted from the Vector after it is added to the Vector, the easiest way is to set the Vector object to null, and o can be recycled by the GC;

 

At this point, all Object objects are not released, because the variable v refers to these objects. At this time, these Objects are unreachable objects, and the GC will not clean them up for us, so there is a memory leak.

 

eg:

Cache system, we load an object in the cache (for example, in a global map object), and then never use it, this object is always referenced by the cache, but is no longer used

 

If a method of an instance object of an outer class returns an instance object of the inner class, the inner class object is referenced for a long time, even if the instance object of the outer class is no longer used, but since the inner class holds the instance object of the outer class, This outer class object will not be garbage collected, which will also cause memory leaks

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326331711&siteId=291194637