Originally posted by jagmohan bisht: Can anyone explain the concept of memory leak in Java.
Technically, a memory leak is not possible in Java, as all deferenced memory should be GC'ed.
However, as an example... A programmer places an object in some collection, to do some processing. Years later, after the original developer left, some other developer changes the processing logic, and forgot about the collection (and for some reason didn't remove the code that places the object into the collection).... then.... is it a memory leak?
It has all the criteria of one. It is constantly growing. The memory is not being freed. And the developer don't know about the reference.
The automatic garbage collection that Java has makes you more productive as a programmer because it automatically handles *much* of the memory management for you -- but it is still possible to have something that you could call a memory leak in Java.
Imagine a Stack object that -- at one time during the run of the java program had a million objects on the stack. Now imagine that you popped-off all of the objects off of the stack. Now, what if you still had a reference to the Stack object and it still has references to a million objects that the Stack object still has a reference to, but that you don't need anymore.
In this case, the stack object should have been programmed to set objects that were in the Stack to null as they are popped-off of the stack so that there is no longer a reference to something that isn't needed. Then automatic garbage collection could reclaim the objects that used to be on the stack if the memory is needed.
An easy solution to this problem with a stack object is to use the Stack object that is already done in the API. For your own data structures, you should ask yourself if an object reference is no longer needed and you can set it to null to make sure that you're not holding on to objects that aren't needed anymore. Then if the memory is needed the automatic garbage collector can collect more garbage. [ January 10, 2008: Message edited by: Kaydell Leavitt ]
straws are for suckers. tiny ads are for attractive people.