What sort of memory leaks are possible in Java and how do I prevent them?
In any language, application-level memory management problems revolve around the deallocation of memory. These problems fall
into two categories: premature deallocation (corrupted pointers) and incomplete deallocation (memory leaks).
In the case of incomplete deallocation, there are two subcases: coding bugs and design bugs. Coding bugs are language dependent.
In the case of C, this would involve free()ing less than was malloc()ed, while in C++ this might involve using delete in lieu of delete[]. Design bugs, on the other hand, do not depend on the language; instead, they involve simple programmer negligence.
In languages like C/C++, all memory management is handled by the programmer, so all of these problems can arise, even after the programmer has expended much effort to ensure the code is free of such defects. In fact, in C/C++ the more you try to avoid memory leaks, the more likely you are to create corrupted pointers, and vice versa. And, by nature the risk of such bugs increases with code size and complexity, so it's difficult to protect large C/C++ applications from these types of bugs.
In Java, on the other hand, the Java language and runtime together entirely eliminate the problems of corrupted pointers and code-level memory leaks. Here's how:
null; the garbage collector will then reclaim all the objects (unless some of the objects are needed elsewhere). This is a lot
easier than coding each of the objects' destructors to let go of its own dependencies (which is a coding-level problem with
C++).
So what about memory leaks caused by poor program design? In such designs, unnecessary object references originating in long-lived parts of the system prevent the garbage collector from reclaiming objects that are in fact no longer needed. Such errors typically involve a failure "in the large" to properly encapsulate object references among various parts of the code.
Another design flaw occurs "in the small," at the level of a faulty algorithm; the use of Collections objects in such cases will typically magnify the error.
As the technology improves, a suitably implemented JVM could help reduce the effects of such designed-in memory leaks by using the garbage collector to track object usage over time. The garbage collector could then rearrange objects in memory according to a freshness factor based on when they were last referenced, for example. Stale objects would become eligible for physical RAM swap-out (even though, for safety, they would still exist).
Helpful piece of information!!!By Anonymous on November 19, 2009, 9:36 pmHelpful piece of information!!!
Reply | Read entire comment
View all comments