Are memory leaks totally absent in Java applications?
Possible Duplicate:
Creating a memory leak with Java
There is a "Garbage Collector" in Java, but does this mean that memory leaks are totally absent in a Java applications? If not, how and why do they happen?
I am more interested in scenarios in applications using JavaSE.
No - memory leaks can still exists in Java. They are just of a "different kind".
Wiki: Memory Leak
A memory leak, in computer science (or leakage, in this context), occurs when a computer program consumes memory but is unable to release it [the memory] back to the operating system .
In the case of Java it (normally) is when an unused/unneeded object is never made eligible for reclamation. For instance, an object may be stashed in a global List and never removed even if the object is never accessed later. In this case the JVM won't release the object/memory - it can't - because the object might be needed later, even if it never is.
(As an aside, some objects, such as directly allocated ByteBuffers also consume "out of JVM heap" memory which might not be reclaimed in a timely manner due to the nature of finalizers and memory pressure.)
In the case of Java, a "memory leak" is a semantic issue and not so much an issue of "not being able to release under any circumstances". Of course, with buggy JNI/JNA code, all bets are off ;-)
Happy coding.
Depends on how you define memory leak.
If you specifically mean having allocated memory that is no longer referenced by some memory root, then no, the garbage collector will eventually clean all of those up.
If you mean generally having your memory footprint grow without bound, that is easily possible. Just have some collection referenced by a static field and constantly added to.
Memory leaks in java are very possible. Here is a good article which has an example using core java. Fundamentally, a memory leak happens in java when the garbage collector cannot reclaim an object because the application holds a reference to it that it won't release, even though the object itself might no longer be used. The easiest way to create a memory leak in java is to have your application hold a reference to something, but not using it.
In the example, the unused object is a static List, and adding things to that list will eventually cause the JVM to run out of memory. Static collections are a pretty common source of "leaks", as they are typically long lived and mutable.
链接地址: http://www.djcxy.com/p/19892.html下一篇: Java应用程序中完全没有内存泄漏?