Saturday, 22 November 2008

Item 6: Eliminate obsolete object references

Item 6 discusses the need to think about memory management even in a garbage-collected language. In the example of the Stack, a "memory leak" exists due to the handling of the internal array. The array keeps track of the number of active elements in the array and increases or decreases when the user pushes a new element or pops it out. But when popping out, the referenced element still stays in the array. So the garbage collector does not know to reclaim the elements. The point is that as a programmer, you can't just stop thinking about memory usage even in a garbage collected system.

It is interesting that the book calls this a memory leak. My experience with C++ is when something overwrites memory used by another object creating corruption, memory leaking from one part of the code to another. The book's example seems to be inefficient use of memory, not clearing it when it is no longer needed. I like the other term the book uses "unintentional object retentions" better.

In the example, the problem was that the stack was managing its own memory, containing a storage pool of the elements, Some could be eventually obsolete. So in these cases, the programmer should be alert for memory leaks. The general solution is to null out the object references once they are no longer needed. But nulling out object references should be rare, normally taken care of by the garbage collector.

The book continues with other common sources of memory leaks like caches, listeners and callbacks. I am not that familiar with caches. As the book describes them, they seem to be storage for quick retrieval. So an object can be placed in a cache and forgotten. A solution is to store only weak references to them. Listeners and callbacks can have a similar problem, you register them but don't deregister them.

I don't have any specific personal comments since I have not used Java, but trying to learn on my free time.

Tim Wright

No comments: