What is a memory leak?
- Generalized memory Leak: The application consumes RAM, but it is no longer used (including the inability to use) that part of the memory
- The narrow memory Leak: The application allocates RAM, but can no longer get a reference to that part of memory (for Java, it cannot be GC)
A concrete example:
- The app creates a long-running thread
- The thread uses ClassLoader (which can be either custom or default) to load a class
- This class has a static field that points to a large chunk of memory, and then the thread's threadlocal variable holds a reference to the class.
- Finally, the thread cleans up references to all loaded classes
- Repeat the above process.
explanation : A memory leak was caused because threadloal saved a reference to that class instance, and the class instance holds a reference to its classloader. This classloader holds references to all of its loaded classes, so that the memory they occupy is not available during the tread run. (usually class loading information is stored in PermGen (permanent generation), this partition generally does not do GC, if necessary to add additional parameters when the Java boot:- XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled
) This is why the application container such as Tomcat to redeploy the application, Causes a memory leak.
The following is a list of some bad programming paradigms that lead to generalized memory leaks:
Get the hash table, and go to Riga key, do not use the time when not deleted; Similarly, a static domain of a class is a hashtable, and keeps moving to the Riga element
Map map = system.getproperties (); Map.put (new// Memory leak Even if your threads die.
Connection,statement and resultset in JDBC forgot to close
String. Intern () allocates memory in the storage pool, and you can't remove them
It is much more difficult to construct a narrow-sense memory leak, and if a pure Java program does not save a reference to that part of memory, the GC will definitely be able to reclaim that portion of memory. So, now it's only possible that Java Nativecode (c + +) caused a memory leak, and that's another topic.
Resources:
Stack overflow High ticket question: How do I create a memory leak bug in Java?
Stack Overflow:permgen Space Overflow error How to solve?
An example of an IBM blog that doesn't have a timely remove hash table key
Why and when to use variables of type thradlocal
Analysis of memory leak problem in Java program