Cause of Java memory leak:
A memory leak refers to a useless object (an object that is no longer being used) that keeps memory or useless objects from being released in a timely manner, resulting in a waste of memory space known as a memory leak.
Long life-cycle objects that hold references to short life-cycle objects are likely to have a memory leak, although a short life-cycle object is no longer needed, but because a long life cycle holds its reference and cannot be recycled, this is the scenario where memory leaks occur in Java.
Several scenarios that cause a memory leak:
1. Memory leak caused by static collection class
Uses such as HashMap, vectors, and so on are the most prone to memory leaks, and the lifetime of these static variables is consistent with the application, and all objects referenced by them cannot be freed because they will always be referenced by vectors.
2. When the object property inside the collection is modified, the Remove () method does not work when it is called.
3. Listener
Not removing these listeners while releasing the object increases the chance of a memory leak.
4. Various connections
For example, a database connection (Datasourse.getconnection ()), a network connection (socket), and an IO connection are not automatically reclaimed by GC unless it explicitly calls its close () method to close its connection.
5. References to internal classes and external modules
The reference to the inner class is a relatively easy one to forget, and once it is not released it can cause a series of subsequent class objects not to be released. In addition, the programmer should be careful of the external module inadvertently reference, such as programmer A is responsible for a module, a method called the B module, such as: public void registermsg (Object b); This call will be very careful, passing in an object, it is likely that module B will maintain a reference to the object, it is important to note that Module B provides the appropriate action to remove the reference.
6. Single Case mode
Improper use of Singleton mode is a common problem that causes a memory leak, and a singleton object will exist in the JVM's lifetime (in the form of a static variable) after it is initialized, and if the singleton object holds an external reference, the object will not be properly reclaimed by the JVM, resulting in a memory leak.
Several possibilities for memory leaks in Java