A memory leak is an object or variable that is no longer being used by the program and consumes storage space in memory.
In the Java language, there are two criteria for determining whether a memory space is eligible for garbage collection :
① gives null value to the object and has not been used in the future;
② assigns a new value to the object and allocates memory space.
There are two types of memory leaks :
① the space requested in the heap is not released; (garbage collection mechanism can solve the problem effectively)
The ② object is no longer in use, but still remains in memory. (This is mostly the case with memory leaks in Java)
There are several reasons why memory leaks are likely to be caused by the following:
1) Static collection classes, such as hashmap and vectors. If these containers are static, because their lifecycle is consistent with the program, the objects in the container will not be freed until the program ends, causing a memory leak.
As shown below:
Vector v=new vector (ten); for (int i=0;i<10;i++) {object o=new Object (); V.add (o);}
2) Various connections, such as database connection, network connection and IO connection.
In the process of operating the database, you need to establish a connection to the database (Connection,statement,resultset), when no longer in use, you need to call the Close method to release the connection, only after the connection is closed, the garbage collector will reclaim the corresponding object.
3) Listener
4) The scope of the variable is unreasonable
If the scope of a variable definition is greater than its scope of use, it is likely to cause a memory leak, and on the other hand, a memory leak can occur if the object is not set to NULL in a timely manner.
5) Singleton mode may cause memory leaks
classbigclass{//class Body}classsingleton{Privatebigclass BC;Private StaticSingleton instance =NewSingleton (NewBigclass ());PrivateSingleton (bigclass BC) { This. bc=BC;} PublicSingleton getinstance () {returninstance}}
Java Memory leak issues