How does memory leak happens in Java? As far as I know, predefined classes such as ArrayList, Vectors might grow indefinitely in a program that isn't well written. However, that is "intended" by the programmer, unless they are careless. Will there be memory leak if there are 2 objects that points to each other, and both are inaccessible by any threads? Or, simply, memory leak in Java only means higher than normal usage of large objects and are GCed at higher frequency? i.e. Memory leaks are never fatal but just a performance factor. Can someone gives a sample code demonstrating memory leak? Chu
The code which uses native approach (JNI) may cause memory leaks, especially the code which is not come from standard JDK distribution. Btw, memmory leaks cases happen usually because of programmer's fault: holding unnecessary object references without releasing them, and the most cases happened when using Threads. A thread will hold the object inside it until it died. So, if you are unaware that your code keep creating bunch of threads and let them run forever, then your RAM will keep decreasing until JVM crash (the out of memmory ERROR thrown). Btw, java's garbage collector is smart enough to detect two or more objects which point to each other. They will be garbage collected if the enclosing Object (the object which wraps them) or the enclosing Thread (the thread which hold their references) is garbage collected. [ June 11, 2002: Message edited by: Alexander Yanuar Koentjara ]
===================================<br />Fear not, God know the best.<br />SCJP2 91%<br />SCWCD 89%<br />SCJD2 92% (143/155 pts)<br />SCEA Part I (89%)
Alexander gave he general principle, that if you hold object references, then they don't get collected. Threads are one common source of this. Another are references in static objects. Even if you destroy all the instances of the class, the static references in the class remain (until the class is unloaded, I think--I can't recall off the top of my head how to compensate for this). Also check out: http://www-106.ibm.com/developerworks/java/library/j-leaks/?dwzone=java
What Mark said is true -- static references to objects will remain around until the class itself is unloaded. With jdk 1.2 and beyond, Class-unloading will only occur if the ClassLoader that loaded the class is itself gc'ed. What this means is that classes loaded by the classpath classloader will never be unloaded. However if you use a separate classloader to load your classes, then nulling out the classloader reference will enable the JVM to unload those classes.
Even if you destroy all the instances of the class, the static references in the class remain (until the class is unloaded, I think--I can't recall off the top of my head how to compensate for this). --Mark
[ June 11, 2002: Message edited by: Junaid Bhatra ]